Ошибки в Java проверяются на ввод целого числа - PullRequest
1 голос
/ 12 апреля 2020

Я знаю, что вопрос был задан, но я попытался применить то, что увидел здесь, и получил ошибку.

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();

    }
}

Без l oop все работает нормально. Что не так в моем коде? Чтобы было ясно, я пытаюсь запросить ввод, пока он не будет проверен как целое число.

Заранее большое спасибо.

Ответы [ 2 ]

2 голосов
/ 12 апреля 2020

Если вы хотите пропустить недействительные не-int значения, ваш l oop должен выглядеть следующим образом:

    while (!get_input.hasNextInt()) {
        // skip invalid input
        get_input.next();
    }
    // here scanner contains good int value  
    year_of_birth = get_input.nextInt();
0 голосов
/ 12 апреля 2020

Это работает для меня, если я вас правильно понял. Вам необходимо постоянно проверять, какое значение имеет сканер, поэтому вам нужно постоянно перемещаться через сканер, пока значение не является целым числом:

        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

...