package w3school;
import java.util.Random;
import java.util.Scanner;
public class nyttprogram {
static void indata() {
{
Scanner determinedNumber = new Scanner(System.in);
int user, computer, number, user2;
System.out.println("Input a number from 0-10");
user = determinedNumber.nextInt();
Random random = new Random();
int randomInt = random.nextInt(10);
if (user == randomInt) {
System.out.println("You guessed the correct number!");
} else {
System.out.println("You guessed the wrong number");
System.out.println("The correct number was: " + randomInt);
}
System.out.println("Input 1 if you want to try again: ");
}
}
public static void main(String[] args) {
indata();
}
}
[如何在用户输入1时使班级重新开始,或者如果用户从头输入错误的数字,班级是否可以重新开始,非常感谢
[如何在用户输入1时使班级重新开始,或者如果用户从头输入错误的数字,班级是否可以重新开始,非常感谢
while
和do/while
循环实现的。1
不同。do/while
。这将运行一次迭代,然后根据所需条件进行检查。private static void inData() {
Scanner userInputScanner = new Scanner(System.in);
Random random = new Random();
// Declare the stop/continue condition
boolean isLoopContinue;
do {
// Generate a random number
int expectedNumber = random.nextInt(10);
// Ask the user to guess a number
System.out.println("Input a number from 0-10");
int givenNumber = userInputScanner.nextInt();
if (givenNumber == expectedNumber) {
// Correct answer, check if the user wants to continue
System.out.println("You guessed the correct number!");
System.out.println("\nInput 1 if you want to try again: ");
// If they input "1", then we continue. Else we stop
isLoopContinue = userInputScanner.nextInt() == 1;
} else {
// Wrong answer, loop again
System.out.println("You guessed the wrong number");
System.out.println("The correct number was: " + expectedNumber);
isLoopContinue = true;
}
} while (isLoopContinue);
}
[如何在用户输入1时使班级重新开始,或者如果用户从头输入错误的数字,班级是否可以重新开始,非常感谢
while
和do/while
循环实现的。1
不同。do/while
。这将运行一次迭代,然后根据所需条件进行检查。private static void inData() {
Scanner userInputScanner = new Scanner(System.in);
Random random = new Random();
// Declare the stop/continue condition
boolean isLoopContinue;
do {
// Generate a random number
int expectedNumber = random.nextInt(10);
// Ask the user to guess a number
System.out.println("Input a number from 0-10");
int givenNumber = userInputScanner.nextInt();
if (givenNumber == expectedNumber) {
// Wrong answer, loop again
System.out.println("You guessed the correct number!");
isLoopContinue = true;
} else {
// Correct answer, check if the user wants to continue
System.out.println("You guessed the wrong number");
System.out.println("The correct number was: " + expectedNumber);
System.out.println("\nInput 1 if you want to try again: ");
// If they input "1", then we continue. Else we stop
isLoopContinue = userInputScanner.nextInt() == 1;
}
} while (isLoopContinue);
}