如何检查userInput是否为整数

huangapple go评论72阅读模式
英文:

How to check if userInput is an int

问题

import java.util.*;

public class ForLoopPractice {
    public static void main(String[]args) {
        Scanner scnr = new Scanner(System.in);
        final int MAX_VALUE;
        System.out.println("打印偶数值");
        System.out.print("最大值:");
        MAX_VALUE = scnr.nextInt();
        
        for (int i=0; i < MAX_VALUE; i++) {
            if (i % 2 == 0) {
                System.out.println(i + " ");
            }
        }
        while (!scnr.hasNextInt()) {
            System.out.println("无效的值");
            scnr.next();
        }
        System.out.println();
        System.out.println("打印一定范围的值");
        System.out.print("第一个值:");
        int firstVal = scnr.nextInt();
        
        System.out.print("最后一个值:");
        int secondVal = scnr.nextInt();
        
        for (int i = firstVal; i >= secondVal; i--) {
            System.out.println(i+ " ");
        }
        for (int i = firstVal; i <= secondVal; i++) {
            System.out.println(i+ " ");
        }
    }
}
英文:

I am trying to output "Invalid value" if the MAX_VALUE I have is not an integer. Whenever I run this code, my overall output gets changed. I am wondering how to correctly do this.

import java.util.*;
public class ForLoopPractice {
public static void main(String[]args) {
Scanner scnr = new Scanner(System.in);
final int MAX_VALUE;
System.out.println(&quot;Print even values&quot;);
System.out.print(&quot;Max value: &quot;);
MAX_VALUE = scnr.nextInt();
for (int i=0; i &lt; MAX_VALUE; i++) {
if (i % 2 == 0) {
System.out.println(i + &quot; &quot;);
}
}
while (!scnr.hasNextInt()) {
System.out.println(&quot;Invalid value&quot;);
scnr.next();
}
System.out.println();
System.out.println(&quot;Print a range of values&quot;);
System.out.print(&quot;First Value: &quot;);
int firstVal = scnr.nextInt();
System.out.print(&quot;Last Value: &quot;);
int secondVal = scnr.nextInt();
for (int i = firstVal; i &gt;= secondVal; i--) {
System.out.println(i+ &quot; &quot;);
}
for (int i = firstVal; i &lt;= secondVal; i++) {
System.out.println(i+ &quot; &quot;);
}
}
}

答案1

得分: 1

使用Try-Catch块。如果输入不是数字,Scanner.nextInt()会抛出InputMismatchException

您可以使用一个函数,确保程序在用户选择正确输入之前不会继续执行。

public static int getValidNumber(){
  try{
     Scanner sc = new Scanner(System.in);
     System.out.println("Enter a number: ");
     int num;
     num = sc.nextInt();
     return num;
  } catch (InputMismatchException ex){
    System.out.println("Invalid Input.");
    return getValidNumber();
  }
}
英文:

Use a Try-Catch block. Scanner.nextInt() throws InputMismatchException if the input isn't a number.

You can use a function to make sure the program doesn't go forward until the user has selected the proper input.

public static int getValidNumber(){
try{
Scanner sc = new Scanner(System.in);
System.out.println(&quot;Enter a number: &quot;);
int num;
num = sc.nextInt();
return num;
} catch (InputMismatchException ex){
System.out.println(&quot;Invalid Input.&quot;);
return getValidNumber();
}
}

答案2

得分: 0

你可以使用以下代码将 "MAX_VALUE = scnr.nextInt();" 包装起来:

if (scnr.hasNextInt()) {
    MAX_VALUE = scnr.nextInt();
}

这会在下一个值可以被解释为整数时返回 true。

英文:

You could wrap "MAX_VALUE = scnr.nextInt();" with:

if (scnr.hasNextInt())

It will return true if the next value can be interpreted as an integer.

答案3

得分: -1

在输入时,您可以使用isDigit()方法进行检查。
如果N是用户输入的一个值,请使用System.out.print(Character.isDigit('N'))进行检查;
该方法将提供布尔值。

英文:

While taking the input, you can check it by a method isDigit().
If N is a input given by user, check it by System.out.print(Character.isDigit('N'));
The method will provide boolean value.

huangapple
  • 本文由 发表于 2020年9月19日 04:56:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/63962743.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定