输入了Java校验整数错误

问题描述 投票:1回答:2

我知道有人问过这个问题,但是我尝试应用在这里看到的内容并出现错误。

package com.company;

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner get_input = new Scanner(System.in);
        System.out.println("Enter your name ");
        String name = get_input.nextLine();


        boolean is_int = false;
        int year_of_birth = 0;
        System.out.println("Enter your year of birth");
        while (!get_input.hasNextInt()) {
        // If the input isn't an int, the loop is supposed to run
        // until an int is input.

            get_input.hasNextInt();
            year_of_birth = get_input.nextInt();
        }
        //year_of_birth = get_input.nextInt();

        System.out.println("Enter the current year");
        int current_year=get_input.nextInt();


        int age = current_year-year_of_birth;


        System.out.println("Your name is " + name + " and you are " + age + " year old.");

        get_input.close();

    }
}

没有循环,一切正常。我的代码有什么问题?为了清楚起见,我正在尝试请求输入,直到可以将输入验证为整数为止。

非常感谢。

java loops input
2个回答
0
投票

如果我正确理解你的话,这对我有用。您需要继续检查扫描仪具有什么值,因此当该值不是整数时,需要通过扫描仪继续前进:

        Scanner get_input = new Scanner(System.in);
        System.out.println("Enter your name ");
        String name = get_input.nextLine();

        int year_of_birth = 0;

        System.out.println("Enter your year of birth");
        while (!get_input.hasNextInt()) { //check if it is not integer
            System.out.println("Enter your year of birth"); // ask again
            get_input.next(); //advance through the buffer
        }
        year_of_birth = get_input.nextInt(); //here you get an integer value
        int current_year=get_input.nextInt();
        int age = current_year-year_of_birth;
        System.out.println("Your name is " + name + " and you are " + age + " year old.");

        get_input.close();

enter image description here


2
投票

如果要跳过无效的非整数值,则循环应如下所示:

    while (!get_input.hasNextInt()) {
        // skip invalid input
        get_input.next();
    }
    // here scanner contains good int value  
    year_of_birth = get_input.nextInt();
© www.soinside.com 2019 - 2024. All rights reserved.