我如何将 int 转换为 char?就像我的问题中的猜测
How can i convert int to char? as in guess in my question
如何将 while (guess != 404)
更改为 char
,如 (guess != Q)
?有可能这样做吗?如果是,请帮助我。所以当我输入 Q 时,它不应该进行到下一个。
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int answer, guess, attemptsNum = 0;
final int maxAttempts = 5;
String str, another = "y";
Scanner scan = new Scanner(System.in);
Random generator = new Random();
answer = generator.nextInt(5) + 1;
while (another.equals("y") || another.equals("Y")) {
System.out.println("Guess a number between 0 and 5");
System.out.println("Enter your guess (404 to quit):");
guess = scan.nextInt();
attemptsNum = 0;
while (guess != 404)
{
attemptsNum++;
if (guess == answer) {
System.out.println("Right!");
break;
} else if (guess != answer)
System.out.println("Wrong");
if (attemptsNum == maxAttempts) {
System.out.println("The number was " + answer);
break;
}
System.out.println("Enter your guess (0 to quit):");
guess = scan.nextInt();
}
System.out.println("Want to Play again?(y/n)");
another = scan.next();
}
System.out.println("Thanks for playing");
}
}
使用scan.next()
其中returns一个String
:
guess = scan.next();
那么你可以这样做:
while (!guess.equals("Q")){
...
}
此外,您可能想看看 String.equalsIgnoreCase()
。
如何将 while (guess != 404)
更改为 char
,如 (guess != Q)
?有可能这样做吗?如果是,请帮助我。所以当我输入 Q 时,它不应该进行到下一个。
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int answer, guess, attemptsNum = 0;
final int maxAttempts = 5;
String str, another = "y";
Scanner scan = new Scanner(System.in);
Random generator = new Random();
answer = generator.nextInt(5) + 1;
while (another.equals("y") || another.equals("Y")) {
System.out.println("Guess a number between 0 and 5");
System.out.println("Enter your guess (404 to quit):");
guess = scan.nextInt();
attemptsNum = 0;
while (guess != 404)
{
attemptsNum++;
if (guess == answer) {
System.out.println("Right!");
break;
} else if (guess != answer)
System.out.println("Wrong");
if (attemptsNum == maxAttempts) {
System.out.println("The number was " + answer);
break;
}
System.out.println("Enter your guess (0 to quit):");
guess = scan.nextInt();
}
System.out.println("Want to Play again?(y/n)");
another = scan.next();
}
System.out.println("Thanks for playing");
}
}
使用scan.next()
其中returns一个String
:
guess = scan.next();
那么你可以这样做:
while (!guess.equals("Q")){
...
}
此外,您可能想看看 String.equalsIgnoreCase()
。