仅限整数限制? [英] Integer-restricted only?

查看:133
本文介绍了仅限整数限制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I limit the input to only integers (no doubles etc)? simple question for someone experienced to answer. if input is anything other than double then display error message, with ability to enter input again

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.");

    }
 }


推荐答案

好的我做了这个:

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
有问题再试一次
插入年数:..
有问题再试试
Insert年数:2
即1051200分钟。

Insert number of years: dsds There is a problem try again Insert number of years: .. There is a problem try again Insert number of years: 2 That is 1051200 in minutes.

这篇关于仅限整数限制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆