Java 如果用户跳过输入,则使用默认值
我想向用户询问数组的大小。如果用户没有输入大小并按enter按钮,我希望使用数组大小作为10(默认值)。我做不到。 这是我的简单java代码 查看图像以供参考Java 如果用户跳过输入,则使用默认值,java,Java,我想向用户询问数组的大小。如果用户没有输入大小并按enter按钮,我希望使用数组大小作为10(默认值)。我做不到。 这是我的简单java代码 查看图像以供参考 我是java初学者。问题是,sc.nextInt()就一直在等待 解决问题的一种方法是读取整行代码,然后尝试将这行代码解析为int 如果用户输入不是int(例如abcdefg或空字符串(仅输入按钮)),则解析将失败。因此,在catch块中设置默认值 例如,它可能看起来像这样: String sizeString=sc.nextLine(
我是java初学者。问题是,
sc.nextInt()只要能找到int
输入,code>就一直在等待
解决问题的一种方法是读取整行代码,然后尝试将这行代码解析为int
如果用户输入不是int(例如abcdefg
或空字符串(仅输入按钮)),则解析将失败。因此,在catch
块中设置默认值
例如,它可能看起来像这样:
String sizeString=sc.nextLine();
整数大小;
试一试{
size=Integer.parseInt(sizeString);
}捕获(数字格式){
尺寸=10;
}
如果您使用nextLine()
而不是nextLine()
,您可以通过将输入与空字符串进行比较来检查是否按下了enter键
Scanner sc = new Scanner(System.in);
System.out.print("Enter the size of Stack: ");
// The replaceAll cleans the input by removing all non numeric characters
String input = sc.nextLine().replaceAll("[^0-9]", "");;
int size;
// If the input is empty set size to 10 otherwise parse the string input as an integer
if(input.equals("")){
size = 10;
}else{
size = Integer.parseInt(input);
}
System.out.println(size);
输出:
Enter the size of Stack:
10
nextInt
非常直白:它希望用户输入一个int
,直到用户输入后才返回。使用类似于nextLine
的方法从用户处获取输入,然后检查输入是否为空,并仅在不为空时将其解析为int。另外:我要避免使用扫描仪:它实际上并不适合用户输入。
Enter the size of Stack:
10