我编写的代码可以编译,但不会产生我期望的输出。在我输入所有输入数据之前,它结束了,并且没有给我正确的输出。知道错误在哪里吗?
这是主程序:
public static void main(String[]args)
{
Scanner keyboard = new Scanner(System.in);
String coinFlip;
int tossNumber, numberOfHeads, numberOfTails;
float percHeads, percTails;
tossNumber = 1;
numberOfHeads = 0;
numberOfTails = 0;
while(tossNumber <= 8)
{
System.out.println("Please toss your coin and enter the side showing.");
System.out.println("h = heads, t = tails");
coinFlip = keyboard.next();
if(coinFlip.equals("h") || coinFlip.equals("t"))
{
if(coinFlip.equals("h"))
{
System.out.println("Thank you! Please toss your coin again.");
tossNumber = tossNumber + 1;
numberOfHeads = numberOfHeads + 1;
}
else
System.out.println("Thank you! Please toss your coin again");
tossNumber = tossNumber + 1;
numberOfTails = numberOfTails + 1;
}
else
System.out.println("Please enter a \"h\" or \"t\".");
}
最佳答案
我所做的就是将{}
添加到您的else
中,我完美地做到了8次,希望如此。
import java.util.Scanner;
public class MC_GAMAD {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String coinFlip;
int tossNumber, numberOfHeads, numberOfTails;
float percHeads, percTails;
tossNumber = 1;
numberOfHeads = 0;
numberOfTails = 0;
while (tossNumber <= 8) {
System.out
.println("Please toss your coin and enter the side showing.");
System.out.println("h = heads, t = tails");
coinFlip = keyboard.next();
if (coinFlip.equals("h") || coinFlip.equals("t")) {
if (coinFlip.equals("h")) {
System.out
.println("Thank you! Please toss your coin again.");
tossNumber = tossNumber + 1;
numberOfHeads = numberOfHeads + 1;
} else {
System.out
.println("Thank you! Please toss your coin again");
tossNumber = tossNumber + 1;
numberOfTails = numberOfTails + 1;
}
} else {
System.out.println("Please enter a \"h\" or \"t\".");
}
}
}
}
关于java - 循环行为不符合我的预期,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33398590/