我对Java编程非常陌生,我正在尝试制作一个扑克手评算器。我正在使用for循环询问一张牌的花色和价值。由于某些原因,它在For循环的第一次迭代中工作,但在那之后只要求我输入一个值。下面是我的代码:
import java.util.Scanner;
public class PokerRun {
public static void main(String[] args) {
int [] suit = new int[5];
int [] value = new int[20];
Card card1 = new Card();
Scanner in = new Scanner(System.in);
int counter = 1;
System.out.println("Welcome to the Poker Hand Evaluator!");
for(int i = 1; i<6; i++)
{
System.out.println("What is the suit of card " + i + "?\nPlease type the suit in all lowercase letters: ");
card1.suit = in.nextLine();
System.out.println("What is the value of card " + i + "? (J = 11, Q = 12 K = 13, A = 14");
card1.value = in.nextInt();
//checks if face card, if true, then changes card.facecard
if(card1.value == 11)
card1.facecard = "Jack";
else if(card1.value == 12)
card1.facecard = "Queen";
else if(card1.value == 13)
card1.facecard = "King";
else if(card1.value == 12)
card1.facecard = "Ace";
if(card1.value<11)
System.out.println("You entered a " + card1.value + " of " + card1.suit + ".");
else
System.out.println("You entered a " + card1.facecard + " of " + card1.suit + ".");
}
}
}发布于 2013-07-25 22:27:12
Rohit Jain,是的,就是这个问题。
我对解决方案的建议是交换线路
card1.value = in.nextInt();
通过以下方式:
card1.value= Integer.parseInt(in.nextLine());
这对你来说应该是可行的。
为了更好地解释它,Scanner被构建用于字符串解析文件等。它对于命令行输入并不是很好。我会使用BufferedReader:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
reader.readLine();发布于 2013-07-25 22:35:02
当您从Scanner类调用next方法时,如果没有可用的输入,它将冻结程序,直到您按enter键(并输入新行字符)。然而,当它解冻程序时,如果对next方法的调用没有使用所有的输入,它将继续运行任何未来的next命令,直到用完为止。只有到那时,它才会再次等待enter命令。
在这种情况下,nextInt命令的输入与下一次迭代的nextLine命令重叠。
向您展示我的意思(因为那只是单词) ->
假设你输入了
菱形,然后按enter键。
这将输入到程序中
‘菱形\n’
第一次调用in.nextLine();将吸收新行之前的每个字符,因此card1.suit = "Diamond“。
接下来,假设您输入数字3,然后按enter键。
这将输入
'3\n‘
对in.nextInt();的调用将吸收数字末尾之前的每个字符。但是,它不会吸收新行,因此
card1.value将等于3。
但是,它仍然必须对其余输入'\n‘做一些操作
因此,当它到达循环的下一次迭代时,对in.nextLine()的第二次调用将吸收直到'\n‘为止的每个字符,也就是说,空格。
所以现在card1.value = "“
要解决这个问题,可以在调用in.nextLine()之后添加对in.nextInt()的调用,也可以使用Integer.parseInt(in.nextLine())。
https://stackoverflow.com/questions/17860658
复制相似问题