【问题标题】:Test to see if input is a positive integer [duplicate]测试输入是否为正整数[重复]
【发布时间】:2016-12-23 11:35:40
【问题描述】:

好吧,我似乎无法为我的问题找到明确的答案。

我需要一个java程序,它可以返回一个用户输入的值,即一个正整数。

为了将此与许多其他类似问题区分开来,我需要编程以在输入字符串时不会崩溃。该程序将需要重复提示用户输入,直到输入一个正整数。脚本是这样的:

Input: 7.2
Error, try again: -5
Error, try again: -2.4
Error, try again: 3.77777
Error, try again: -1
Error, try again: 0
Error, try again: -33
Error, try again: microwave
Error, try again: -1
Error, try again: 4.2
Error, try again: hello
Error, try again: 3.14159
Error, try again: 4
4 is a positive integer.

重要的是当输入诸如单词之类的内容时程序不会崩溃。我想不出一种方法让程序做这样的事情。我可以将hasNextInt 与扫描仪一起使用,但是我不知道如何检查它是否大于零,因为在另一种情况下输入可能是字符串。

有人可以帮我开发一个可以返回上述脚本的程序吗?非常感谢。

编辑:好的,我终于在另一个问题中找到了我正在寻找的答案。这个解决方案不使用parseInt(),也不使用try/catch,这正是我要找的。很好很简单。所以这里是解决方案代码:

    Scanner in = new Scanner(System.in);
    int num;
    System.out.print("Input: ");
    do {
        while (!in.hasNextInt()) {
            System.out.print("Error, not integer. Try again: ");
            in.next(); 
        }
        num = in.nextInt();
        if (num<=0){
            System.out.print("Error, not positive. Try again: ");
        }
    } while (num <= 0);
    System.out.println(num + " is a positive integer.");

【问题讨论】:

  • 读入nextLine,使用try-catch并解析为Integer,捕获异常。如果没有出现异常,检查num&lt;0?
  • @KevinEsche 对try-catch 不太熟悉,你能详细说明一下,并告诉我它是如何在代码中使用的吗?对不起,我不是很聪明:(

标签: java string int java.util.scanner


【解决方案1】:

试试这个方法:

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int value = -1;
    do {
        System.out.print("Input: ");
        String input = scanner.next();
        try {
            value = Integer.parseInt(input);
        } catch (NumberFormatException e) {
            System.out.println("Error, try again: " + input);
        }
    } while (value < 1);
    System.out.println(value + " is a positive integer.");
}

【讨论】:

  • 我需要学习更多的 java :( 但是谢谢你这个工作!
  • 现在它是可执行的并且接近您的要求。是的,学习 Java!
【解决方案2】:

这里有一个link 用于java 中的异常处理。通常,您只需将代码放入 try 块中。然后,如果该块中发生预期的异常,您的程序将执行 catch 块中的代码并继续它的工作。

【讨论】:

  • 这个链接非常有用,谢谢!
【解决方案3】:

您需要以某种方式验证输入。如果您输入的是Integer。那么您需要将其打印到屏幕上,如果您输入的是Long,那么您需要打印错误消息Try again

在下面的示例中,我创建了一个方法,它是 C# TryParse 方法的派生方法。 C# TryParseInt

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        while (true)
        {
            @SuppressWarnings("resource")
            Scanner reader = new Scanner(System.in); 
            System.out.println("Enter a number: ");

            String input = reader.next();
            tryParseInt(input);
        }
    }

    private static void tryParseInt(String input) {  
        try {  
            int val = Integer.parseInt(input);
            System.out.println(val + " is a positive Integer");
        } catch (NumberFormatException e) {
            System.out.println(input + " Is not a number/positive Integer, " + e.getMessage());
        }  
    }
}

它的作用是将输入解析为Integer,如果由于输入为String 或不是有效的正数Integer 而无法解析,则抛出NumberFormatException。然后我可以打印我想要的错误消息。

祝你好运!

【讨论】:

    【解决方案4】:

    以下是两种情况:

    场景 1:
    - 我假设正整数是指整数 1、2、3、4 等...
    - 4.00 等值不会被视为整数

    import java.util.Scanner;
    
    public class Main {
    
        public static void main(String[] args) {
    
            Scanner scanner = new Scanner(System.in);
            int value = 0;
            System.out.print("Input: ");
    
            while (value < 1){
                String input = scanner.next();
                try {
                    value = Integer.parseInt(input);
                    if(value < 1){
                        System.out.print("Error, try again: ");}
                } catch (NumberFormatException e) {
                    System.out.print("Error, try again: ");
                }
            }
            System.out.println(value + " is a positive integer.");
        }
    }
    

    场景 2:
    - 我假设正整数是指整数 1、2、3、4 等...
    - 4.00 等值将被视为整数

    import java.math.BigDecimal;
    import java.util.Scanner;
    
    public class Main {
    
        public static void main(String[] args) {
    
            Scanner scanner = new Scanner(System.in);
    
            System.out.print("Input: ");
            String value = "";
            boolean positiveIntegerNoDecimals = false;
            while (positiveIntegerNoDecimals == false) {
                value = scanner.next();
                positiveIntegerNoDecimals = isPositiveIntegerNoDecimals(value);
    
                if (positiveIntegerNoDecimals == false)
                    System.out.print("Error, try again:");
            }
            System.out.println(value + " is a positive integer.");
        }
    
        private static boolean isPositiveIntegerNoDecimals(String input) {
            try {
                int value = -1;
                BigDecimal decimal = new BigDecimal(Double.parseDouble(input));
                int scale = decimal.scale();
                if (scale == 0)
                    value = decimal.stripTrailingZeros().intValue();
    
                if (value > 0)
                    return true;
            } catch (NumberFormatException e) {}
            return false;
        }
    }
    

    【讨论】:

      【解决方案5】:

      Integer.parseInt(String s)

      就是为此而写的。

      【讨论】:

      • 我不熟悉那个方法,你能告诉我它是如何在程序中使用的吗?
      • 向我们展示一些您使用过扫描仪的代码?我将准确指导您在何处以及如何使用它。
      • “正整数”
      猜你喜欢
      • 2014-11-29
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 2017-10-30
      • 1970-01-01
      • 2017-07-21
      相关资源
      最近更新 更多