仅限整数限制?

时间:2017-03-11 22:24:40

标签: java integer

如何将输入限制为只有整数(没有双打等)?有经验的人回答的简单问题。如果输入不是double,则显示错误信息,能够再次输入

import java.util.Scanner;


public static void main(String[] args) {

    Scanner reader =  new Scanner(System.in);
    int years;
    int minutes;

    System.out.println("Years to Minutes Converter");
    System.out.print("Insert number of years: ");
    years = reader.nextInt();

    minutes = years * 525600;


    System.out.print("That is ");
    System.out.print(minutes);
    System.out.print(" in minutes.");

    }
 }

2 个答案:

答案 0 :(得分:1)

使用Scanner.hasNextInt()

如果使用true方法将此扫描仪输入中的下一个标记解释为默认基数中的int值,则返回nextInt()。扫描仪不会超过任何输入。

示例代码:

Scanner sc = new Scanner(System.in);
System.out.print("Enter number 1: ");

while (!sc.hasNextInt()) 
    sc.next();

int num1 = sc.nextInt();
int num2;

System.out.print("Enter number 2: ");

do {
    while (!sc.hasNextInt()) 
        sc.next();
    num2 = sc.nextInt();
} while (num2 < num1);

System.out.println(num1 + " " + num2);

您不必parseInt或担心NumberFormatException。请注意,由于hasNextXXX方法不会超过任何输入,如果您想跳过“垃圾”,可能需要调用next(),如上所示。

答案 1 :(得分:0)

好的,我做到了:

package reader;

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        Scanner reader = new Scanner(System. in );
        int years;
        int minutes;
        String data = null;

        System.out.println("Years to Minutes Converter");
        boolean test = false;

        while (test == false) {
            System.out.print("Insert number of years: ");
            String regex = "\\d+";
            data = reader.next();
            test = data.matches(regex);
            if (test == false) {
                System.out.println("There is a problem try again");
            }
        }
        years = Integer.valueOf(data);

        minutes = years * 525600;

        System.out.print("That is ");
        System.out.print(minutes);
        System.out.print(" in minutes.");

    }

}

它会说:

Years to Minutes Converter

插入年数:dsds 有一个问题再试一次 插入年数:.. 有一个问题再试一次 插入年数:2 那是几分钟内的1051200。