输入值在尝试提示输入时保持为0。

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

input value stays 0 when trying to prompt their input

问题

我正在尝试使用用户输入的值以及错误消息作为提示,如果输入的不是整数,则会出现错误消息。当我尝试提示用户时,如果输入是双精度或字符串,他们的输入保持为 0。

//主方法
public static void main(String[] args) {
    int i = 0;
    //实例化用于用户输入的新 Scanner
    Scanner input = new Scanner(System.in);

    //解析输入,显示值
    //并提示用户输入不是整数
    try {
        int inputNum = Integer.parseInt(input.next());
        System.out.println("输入的值为:" + String.valueOf(inputNum));
    } catch (NumberFormatException e) {
        System.out.println("输入的值为:" + String.valueOf(inputNum));
        System.out.println(String.valueOf(inputNum) + " 不是一个整数。");
    }
}
英文:

I am trying to prompt a user with the value they inputted and an error message if it's not an integer. When I try to prompt them, their input stays 0 when the input is a double or string.

//main method
public static void main(String[] args) {
int i = 0;
//instantiate new Scanner for user input 
Scanner input = new Scanner(System.in);

//parse imput, display value 
//and prompt user that their input is not a int   
try {
   inputNum = Integer.parseInt(input.next());
   System.out.println("Value entered is " + 
String.valueOf(inputNum));      
  } catch(NumberFormatException e) {
     System.out.println("Value entered is " + 
String.valueOf(inputNum));
     System.out.println(String.valueOf(inputNum) + " is not an integer.");
    }
   }
  }

答案1

得分: 2

如果输入是双精度数或字符串,则parseInt会抛出异常,且inputNum不会被分配新值。您可以在将其传递给parseInt之前将input.next()存储在一个字符串中,或者您可能可以在catch块中使用e来找出错误的值。

String s;

//解析输入,显示值
//并提示用户其输入不是整数
try {
   s = input.next();
   System.out.println("输入的值为:" + s);
   inputNum = Integer.parseInt(s);
} catch(NumberFormatException e) {
   System.out.println(s + "不是一个整数。");
}
英文:

If the input is a double or a string then parseInt would throw an exception and inputNum would not be assigned any new value. You could store input.next() in a string before passing it to parseInt - or you might be able to use e in the catch block to figure out the bad value

String s;

//parse imput, display value 
//and prompt user that their input is not a int   
try {
   s = input.next();
   System.out.println("Value entered is " + s);
   inputNum = Integer.parseInt(s);
  } catch(NumberFormatException e) {
     System.out.println(s + " is not an integer.");
    }
   }
  }

答案2

得分: 0

好的,以下是翻译好的部分:

这是一个概念('要求用户输入一些内容,如果无效则继续询问'),您可能希望执行不止一次,因此它不应放在主程序中。

为它创建自己的方法。

这个方法会以一个'提示'作为输入,并返回一个数字。其目的是询问用户(使用该提示)输入一个数字,并在他们输入一个数字之前不断询问。

您可以使用while()循环代码,直到满足某个条件,或者简单地永久循环,使用return来跳出循环,并以一次完成整个'要求用户输入数字'方法。

英文:

Well, it's a concept ('ask user for some input, keep asking if it is not valid') that you may want to do more than once, so it has no business being in main.

Give it its own method.

This method would take as input a 'prompt' and will return a number. The purpose is to ask the user (with that prompt) for a number, and to keep asking until they enter one.

You can use while() to loop code until a certain condition is met, or simply forever, using return to escape the loop and the entire 'ask the user for a number' method in one fell swoop.

答案3

得分: 0

我已根据您的需求修改了代码,使其按照您的要求工作:

    public static void main(String[] args) {
//为用户输入实例化新的扫描器
        Scanner input = new Scanner(System.in);

//解析输入,显示值
//并提示用户输入不是整数
        String inputNum = input.next();
        try {
            System.out.println("输入的值为:" +
                    Integer.parseInt(inputNum));
        } catch (NumberFormatException e) {
            System.out.println("输入的值为:" +
                    inputNum);
            System.out.println(inputNum + "不是整数。");
        }
    }

上面是在Java中检查字符串是否为整数的标准方法。如果您想要一种更简单且功能强大的方式,您可以利用Apache Commons库:

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        final String num = input.next();
        // 检查 num 是否为数字
        if (NumberUtils.isCreatable(num)) {
            System.out.println("输入的值为:" + num);
        } else {
            System.out.println("输入的值为:" + num);
            System.out.println(num + "不是数字。");
        }
    }

请注意,NumberUtils#isCreatable 可以检查各种数字格式(整数、浮点数、科学计数法等)。如果您想要与 Integer#parseIntLong#parseLongFloat#parseFloatDouble#parseDouble 等效的功能,可以使用 NumberUtils#isParsable

英文:

I've modified the code to make it work according to your need:

    public static void main(String[] args) {
//instantiate new Scanner for user input
        Scanner input = new Scanner(System.in);

//parse imput, display value
//and prompt user that their input is not a int
        String inputNum = input.next();
        try {
            System.out.println("Value entered is " +
                    Integer.parseInt(inputNum));
        } catch (NumberFormatException e) {
            System.out.println("Value entered is " +
                    inputNum);
            System.out.println(inputNum + " is not an integer.");
        }
    }

Above is the standard approach to check if a String is an integer in java. If you want a simpler & powerful way you can leverage the Apache Commons library:

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        final String num = input.next();
        // check to see if num is a number
        if (NumberUtils.isCreatable(num)) {
            System.out.println("Value entered is " + num);
        } else {
            System.out.println("Value entered is " + num);
            System.out.println(num + " is not a number.");
        }
    }

Note that NumberUtils#isCreatable checks for a wide variety of number formats(integer, float, scientific...)
If you want something equivalent to Integer#parseInt, Long#parseLong, Float#parseFloat or Double#parseDouble. Use instead, NumberUtils#isParsable.

答案4

得分: 0

有另一种简洁的方法可以在不抛出任何异常的情况下完成,您可以使用 hasNextInt() 来预先验证输入值是否为有效的整数,然后使用 nextInt() 来读取整数而无需解析字符串:

    public static void main(String[] args){

        Scanner scanner = new Scanner(System.in);
        int inputNum;
        if(scanner.hasNextInt()){
            inputNum = scanner.nextInt();
            System.out.println("输入的值是:" + inputNum);
        }else{
            System.out.println(scanner.next() + " 不是整数。");
        }

    }
英文:

There is an another concise way to do it without throwing any exception, you can use hasNextInt() to pre-validate if the input value is a valid integer before hand, then use nextInt() to read an integer without parsing the string:

    public static void main(String[] args){

        Scanner scanner = new Scanner(System.in);
        int inputNum;
        if(scanner.hasNextInt()){
            inputNum = scanner.nextInt();
            System.out.println("Value entered is " + inputNum);
        }else{
            System.out.println(scanner.next() + " is not an integer.");
        }

    }

huangapple
  • 本文由 发表于 2020年10月12日 10:10:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/64310816.html
匿名

发表评论

匿名网友

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

确定