提问人:learning 提问时间:10/17/2020 最后编辑:Arvind Kumar Avinashlearning 更新时间:1/18/2021 访问量:96
如何让 java 中的扫描器读取字符串?[已结束]
How do I get the Scanner in java to read a string? [closed]
问:
当用户输入 q 时,如何让我的程序退出? 扫描仪有问题吗?
我的代码
import java.util.*;
public class Main{
public static void main(String []args){
int age;
Scanner scan = new Scanner(System.in);
System.out.println("Enter your age, or enter 'q' to quit the program.");
age = scan.nextInt();
if(age.equals("q") || age.equals("Q")){
return 0;
}
System.out.println("Your age is " + age);
}
}
答:
0赞
Arvind Kumar Avinash
10/17/2020
#1
我主要可以看到您的代码中的两个问题:
- 它缺少一个循环来重复再次询问年龄。可以有很多方法(、、)来编写循环,但我发现
do-while
最适合这种情况,因为它总是至少执行一次块中的语句。for
while
do-while
do
age
是类型,因此它不能与字符串进行比较,例如您的代码,不正确。处理这种情况的一个好方法是将输入放入 type 变量中,并检查该值是否应该允许/不允许处理它(例如,尝试将其解析为 )。int
age.equals("q")
String
int
请注意,当您尝试解析无法解析为 an 的字符串时(例如),您会得到一个需要处理的字符串(例如显示错误消息、更改某些状态等)。int
"a"
NumberFormatException
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int age;
String input;
Scanner scan = new Scanner(System.in);
boolean valid;
do {
// Start with the assumption that input will be valid
valid = true;
System.out.print("Enter your age, or enter 'q' to quit the program: ");
input = scan.nextLine();
if (!(input.equals("q") || input.equals("Q"))) {
try {
// Try to parse input into an int
age = Integer.parseInt(input);
System.out.println("Your age is " + age);
} catch (NumberFormatException e) {
System.out.println("Invalid input");
// Change the value of valid to false
valid = false;
}
}
} while (!valid || !(input.equals("q") || input.equals("Q")));
}
}
示例运行:
Enter your age, or enter 'q' to quit the program: a
Invalid input
Enter your age, or enter 'q' to quit the program: 12.5
Invalid input
Enter your age, or enter 'q' to quit the program: 14
Your age is 14
Enter your age, or enter 'q' to quit the program: 56
Your age is 56
Enter your age, or enter 'q' to quit the program: q
评论
2赞
Hovercraft Full Of Eels
10/17/2020
请解释这个答案
0赞
Hovercraft Full Of Eels
10/17/2020
请参阅仅包含注释代码的答案是否可接受?
下一个:如何生成整数数字的平方
评论
age.equals("any string")
.equals
int