如何使 Java 中的字符输入无效?
这非常简单,但我是 Java 编程语言的新手,一些指导会有所帮助。我正在制作一个列出选项的菜单。但是,我希望用户键入一个字符作为一种选项,以获得类似此处的文本,并再次将用户返回到选择。
我通过将大小写与默认值混淆来呈现错误。
import java.util.Scanner;
public class selectMenu {
public static void main(String[] args) {
System.out.println("select your option:");
System.out.println("1) showing today menu");
System.out.println("2) showing tomorrow menu");
int op = scanner.nextInt();
switch(op) {
case 1 -> System.out.println("TODAY MENU");
case 2 -> System.out.println("TOMORROW MENU");
case 3 ->
if (option==char) {
System.out.println("This is an invalid option.");
}
default -> System.out.println("Opcion invalida.");
}
}
This is extremely simple, but I am new to the Java programming language and some guidance would be helpful. I am making a menu where the options are listed. However, I would love for the user to type a character as an option to get a text like the one here and return the user to the selection again.
I present errors by confusing the case with the default.
import java.util.Scanner;
public class selectMenu {
public static void main(String[] args) {
System.out.println("select your option:");
System.out.println("1) showing today menu");
System.out.println("2) showing tomorrow menu");
int op = scanner.nextInt();
switch(op) {
case 1 -> System.out.println("TODAY MENU");
case 2 -> System.out.println("TOMORROW MENU");
case 3 ->
if (option==char) {
System.out.println("This is an invalid option.");
}
default -> System.out.println("Opcion invalida.");
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试执行以下操作:
它采用下一行而不是 nextInt() (如果它不是数字,则会抛出异常),检查答案是否为
"1"
或“2”
,然后检查它是否是有效的int
(“3”、“4”等)。如果不是,它会检查长度,如果长度为 1,则告诉您它是一个char
,否则是一个String
。如果您不关心用户实际输入的内容(
char
、String
等),只是他们没有输入 int,您可以移动try
-catch
围绕扫描仪输入:抱歉,如果缩进有点偏离,我不知道为什么会发生这种情况。
You could try doing something like this:
It takes the next line rather than nextInt() (which will throw an exception if it's not a number), checks if the answer is
"1"
or"2"
, then checks if it's a validint
("3", "4", etc). If not, it checks the length, and tells you it's achar
if the length is 1, otherwise aString
.If you don't care about what the user actually entered (
char
,String
, etc), just that they didn't type an int, you could move thetry
-catch
around the scanner input:Sorry if the indenting is a bit off, I don't know why that was happening.