是的,这是一个家庭作业问题。我是编程的初学者。我擅长使用if / else和for循环,因为我的教授要求我们循环。我很困惑。这是问题......
Q1)假设您正在编写一个涉及2位数字的游戏程序,每个数字由2个不同的数字组成。测试是否接受在序列中输入的数字是否在此游戏中使用。测试输入错误(包括类型)。
我的while循环检查数据类型最初工作正常,但是在输入int之后我无法检查数据类型。有人可以向我解释这个问题吗?谢谢......
public static void main(String[] args){
int num = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter a 2-digit number. The digits should be different. zero to stop");
while(!input.hasNextInt()){
System.out.println("Not an integer,try again " + num);
input.next();
}
num = input.nextInt();
while(num != 0){
while(num < 10 || num >= 99){
System.out.println("NOT good for your game! " + num );
System.out.println("Enter a 2-digit number. The digits should be different. Zero to stop");
num = input.nextInt();
}
System.out.println("Good for your game! Play! " + num);
num = input.nextInt();
}
}
}
答案 0 :(得分:0)
第一个中的while循环检查System.in是否正在输入数字(int):while(!input.hasNextInt())
,但是当您第一次输入数字时,循环退出并进入接下来的2个循环:
while(num != 0){
while(num < 10 || num >= 99){
然后在内循环的末尾你有:
num = input.nextInt();
这意味着你已经假设下一个输入是一个int。因此,如果输入非数字输入,程序将抛出异常。
我建议你把整个循环改成:
public static void main(String[] args) {
int num = 1;
Scanner input = new Scanner(System.in);
do {
System.out.println("Enter a 2-digit number. The digits should be different. zero to stop");
if (!input.hasNextInt()) {
System.out.println("Not an integer,try again " + num);
} else {
num = input.nextInt();
if (num < 10 || num >= 99) {
System.out.println("NOT good for your game! " + num);
} else {
System.out.println("Good for your game! Play! " + num);
}
}
} while(num != 0);
input.close();
System.out.println("game stop");
}
答案 1 :(得分:-1)
import java.util.Scanner;
public class Number1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String prompt = "Enter a 2-digit number. The digits should be different. Zero to stop:";
getInt(sc,prompt);
}
public static void getInt(Scanner sc,String prompt) {
System.out.println(prompt);
int num;
while (!sc.hasNextInt())
{
System.out.println("Not an integer, Try again");
sc.next();
}
num = sc.nextInt();
while(num != 0) {
if (num < 10 || num >= 99 || num == 0)
{
System.out.println("Not good for your game!");
}
else
{
System.out.println("Good for your game! Play!");
}
System.out.println(prompt);
num = sc.nextInt();
}
}
}