[英]How do I check a condition within a loop java?
First off I'm new to java and thought I would start by making some smaller programs to help myself learn. 首先,我是Java的新手,并认为我将从编写一些较小的程序来帮助自己学习开始。 So I started a "Don't Step the White Tile" game and I got the printing of each line to print but I need to check whether the user input equals the tile. 因此,我启动了“别踩白块”游戏,并获得了要打印的每一行的打印,但是我需要检查用户输入是否等于该块。 I'm not sure how to go about this because I've tried many things and I'm at a road block. 我不确定该怎么做,因为我已经尝试了很多事情,并且遇到了障碍。
Anything help and thanks in advance. 任何帮助和感谢。
import java.util.Scanner;
public class DontStepTheWhiteTile {
public static void main(String[] args) {
//Variables
int userInput = 0, numberEntered = 0, tileNumber;
char start;
//Scanner
Scanner scanner = new Scanner(System.in);
//Loop for tiles
if (userInput == 0) {
System.out.print("Enter the character 's' to begin: ");
start = scanner.nextLine().charAt(0);
if (start == 's') {
userInput = 1;
}
}
//Starts the time
long timeStart = System.currentTimeMillis();
//Makes the tiles
if (userInput == 1){
for (int i = 0; i <= 25; i++) {
int tile = (int) (3 * Math.random() + 1);
if (tile == 1){
System.out.print("1 | X | X = ");
numberEntered = scanner.nextInt();
}
else if (tile == 2){
System.out.print("X | 2 | X = ");
numberEntered = scanner.nextInt();
}
else {
System.out.print("X | X | 3 = ");
numberEntered = scanner.nextInt();
}
}
}
//Calculates the ending time
long timeEnd = System.currentTimeMillis();
System.out.println("It took you "
+ ((timeEnd - timeStart) / 1000) + " seconds");
}
}
You never test numberEntered
so the users input doesn't change the behavior of the code. 您永远不会测试numberEntered
因此用户输入不会更改代码的行为。 It would be easier to answer your question if you'd made clear what behavior you do want. 如果您清楚了自己想要的行为,就可以轻松回答您的问题。 Since you don't I'm forced to guess. 既然你不这样做,我就不得不猜测。
If you want the game to end on the first miss a break
out of the for
loop will work. 如果你想在游戏中第一个小姐结束break
出来的for
循环会工作。
if (numberEntered != tile) {
System.out.println("You lose");
break;
}
If you want the game to end on say 3 misses, an accumulating int that you test before the break
will work. 如果您希望游戏在3次未击中结束,则在break
之前测试的累积int会起作用。
if (numberEntered != tile) {
misses++;
}
if (misses >= 3) {
System.out.println("You lose");
break;
}
Either way, all this code can go at the end of your for
loop after your current if-else
structure. 无论哪种方式,所有这些代码都可以在当前if-else
结构之后的for
循环末尾进行。
Infact numberEntered = scanner.nextInt();
numberEntered = scanner.nextInt();
can be moved after the if-else
as well since it's the same in every case. 也可以在if-else
之后移动,因为在每种情况下都相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.