0

Помогите решить задачу , нужно сделать через сканер , не понимаю как в метод вложить проверку ведённого значения в консоль

введите сюда описание изображения

public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Input your team: ");
        String team1 = scanner.next();
        System.out.println("Input 1 player frags: ");
        if (scanner.hasNext()) {
            System.out.println("You put the wrong value! ");
            System.exit(0);
        }
        int player1team1 = scanner.nextInt();
        System.out.println("Input 2 player frags: ");
        if (scanner.hasNext()) {
            System.out.println("You put the wrong value! ");
            System.exit(0);
        }
        int player2team1 = scanner.nextInt();
        System.out.println("Input 3 player frags: ");
        if (scanner.hasNext()) {
            System.out.println("You put the wrong value! ");
            System.exit(0);
        }
        int player3team1 = scanner.nextInt();
        System.out.println("Input 4 player frags: ");
        if (scanner.hasNext()) {
            System.out.println("You put the wrong value! ");
            System.exit(0);
        }
        int player4team1 = scanner.nextInt();
        System.out.println("Input 5 player frags: ");
        if (scanner.hasNext()) {
            System.out.println("You put the wrong value! ");
            System.exit(0);
        }
        int player5team1 = scanner.nextInt();

        System.out.print("Input your team: ");
        String team2 = scanner.next();
        System.out.println("Input 1 player frags: ");
        if (scanner.hasNext()) {
            System.out.println("You put the wrong value! ");
            System.exit(0);
        }
        int player1team2 = scanner.nextInt();
        System.out.println("Input 2 player frags: ");
        if (scanner.hasNext()) {
            System.out.println("You put the wrong value! ");
            System.exit(0);
        }
        int player2team2 = scanner.nextInt();
        System.out.println("Input 3 player frags: ");
        if (scanner.hasNext()) {
            System.out.println("You put the wrong value! ");
            System.exit(0);
        }
        int player3team2 = scanner.nextInt();
        System.out.println("Input 4 player frags: ");
        if (scanner.hasNext()) {
            System.out.println("You put the wrong value! ");
            System.exit(0);
        }
        int player4team2 = scanner.nextInt();
        System.out.println("Input 5 player frags: ");
        if (scanner.hasNext()) {
            System.out.println("You put the wrong value! ");
            System.exit(0);
        }
        int player5team2 = scanner.nextInt();

        int avgResultTeam1 = (player1team1 + player2team1 + player3team1 + player4team1 + player5team1) / 5;

        int avgResultTeam2 = (player1team2 + player2team2 + player3team2 + player4team2 + player5team2) / 5;

        if (avgResultTeam1 > avgResultTeam2) {
            System.out.println("Победила команда " + team1 + " набравшая " + avgResultTeam1 + " очков");
        } else {
            System.out.println("Победила команда " + team2 + " набравшая " + avgResultTeam2 + " очков");
        }

        scanner.close();

    }
}
10
  • А что конкретно вы хотите проверить после ввода значений? Вы знаете как работает scanner.hasNext()?
    – had0uken
    7 июл 2022 в 17:29
  • чтобы если ведённы буквы вместо цифр остановило код (Код это неудачная версия этот) и это записать в метод и использовать этот кусок кода
    – Dead356
    7 июл 2022 в 17:31
  • if (scanner.nextLine()) { System.out.println("You put the wrong value! "); System.exit(0); } Я не понимамю как эту строчку сделать методом
    – Dead356
    7 июл 2022 в 17:42
  • и как сделать чтобы если пользователь вводить буквы вместо цифр в консоль оно выбивало ему ошибку
    – Dead356
    7 июл 2022 в 17:44
  • Написал ниже ответ. если пользователь введет буквы вместо числа, при работе метода nextInt() , то получит в консоль исключение InputMismatchException. И программа завершит работу. Если вам важно проверять это условие. То вам нужен метод nextLine() и потом уже проверять полученную строку. - цифры в ней или буквы. В данном варианте до строки int player1team2 = scanner.nextInt(); ваша программа не доходит
    – had0uken
    7 июл 2022 в 17:48

1 ответ 1

0

В вашей программе вы в любом случае попадаете на строку System.exit(0); и программа завершает свою работу. Какой принцип работы метода scanner.hasNext(): данный метод возвращает true пока не закончится поток. При чтении из файла - концом потока будет конец файла. При чтении с клавиатуры концом потока будет ввод ^D (в Windows CTRL+D). То есть вы доходите до строки

if (scanner.hasNext()) {

В ЛЮБОМ случае попадаете в эту ветку и на команде System.exit(0); завершаете программу. Вам нужно убрать эту проверку, потом считывать данные с помощью метода scanner.nextLine() а не nextInt(). И проверять этот nextLine(): цифры там или нет. Вашу проверки с hasNext() удалите все, потому что вы будете в любом случае в них попадать и программа будет завершаться. Попробуйте переписать код без них, если не получится - напишите

Добавил мой вариант исправленного кода:

public class Test2 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Input your team: ");
        String team1 = scanner.next();
        System.out.println("Input 1 player frags: ");
        int player1team1=0;
        try {
             player1team1 = scanner.nextInt();
        }
        catch (InputMismatchException exc) {
            System.out.println("You put the wrong value! ");}

        System.out.println("Input 2 player frags: ");
        int player2team1=0;
        try {
            player2team1 = scanner.nextInt();
        }
        catch (InputMismatchException exc) {
            System.out.println("You put the wrong value! ");}

        int player3team1=0;
        try {
            player3team1 = scanner.nextInt();
        }
        catch (InputMismatchException exc) {
            System.out.println("You put the wrong value! ");}

        System.out.println("Input 4 player frags: ");
        int player4team1=0;
        try {
            player4team1 = scanner.nextInt();
        }
        catch (InputMismatchException exc) {
            System.out.println("You put the wrong value! ");}
        System.out.println("Input 5 player frags: ");
        int player5team1=0;
        try {
            player5team1 = scanner.nextInt();
        }
        catch (InputMismatchException exc) {
            System.out.println("You put the wrong value! ");}

        System.out.print("Input your team: ");
        String team2 = scanner.next();
        System.out.println("Input 1 player frags: ");
        int player1team2=0;
        try {
            player1team2 = scanner.nextInt();
        }
        catch (InputMismatchException exc) {
            System.out.println("You put the wrong value! ");}
        System.out.println("Input 2 player frags: ");
        int player2team2=0;
        try {
            player2team2 = scanner.nextInt();
        }
        catch (InputMismatchException exc) {
            System.out.println("You put the wrong value! ");}
        System.out.println("Input 3 player frags: ");
        int player3team2=0;
        try {
            player3team2 = scanner.nextInt();
        }
        catch (InputMismatchException exc) {
            System.out.println("You put the wrong value! ");}
        System.out.println("Input 4 player frags: ");
        int player4team2=0;
        try {
            player4team2 = scanner.nextInt();
        }
        catch (InputMismatchException exc) {
            System.out.println("You put the wrong value! ");}
        System.out.println("Input 5 player frags: ");
        int player5team2=0;
        try {
            player5team2 = scanner.nextInt();
        }
        catch (InputMismatchException exc) {
            System.out.println("You put the wrong value! ");}

        int avgResultTeam1 = (player1team1 + player2team1 + player3team1 + player4team1 + player5team1) / 5;

        int avgResultTeam2 = (player1team2 + player2team2 + player3team2 + player4team2 + player5team2) / 5;

        if (avgResultTeam1 > avgResultTeam2) {
            System.out.println("Победила команда " + team1 + " набравшая " + avgResultTeam1 + " очков");
        } else {
            System.out.println("Победила команда " + team2 + " набравшая " + avgResultTeam2 + " очков");
        }

        scanner.close();

    }
}

Вариант с методом:

public class Test2 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Input your team: ");
        String team1 = scanner.next();
        System.out.println("Input 1 player frags: ");
        int player1team1 = getValue();
        System.out.println("Input 2 player frags: ");
        int player2team1 = getValue();
        System.out.println("Input 3 player frags: ");
        int player3team1 = getValue();
        System.out.println("Input 4 player frags: ");
        int player4team1 = getValue();
        System.out.println("Input 5 player frags: ");
        int player5team1 = getValue();
        System.out.print("Input your team: ");
        String team2 = scanner.next();
        System.out.println("Input 1 player frags: ");
        int player1team2 = getValue();
        System.out.println("Input 2 player frags: ");
        int player2team2 = getValue();
        System.out.println("Input 3 player frags: ");
        int player3team2 =  getValue();
        System.out.println("Input 4 player frags: ");
        int player4team2 = getValue();
        System.out.println("Input 5 player frags: ");
        int player5team2 = getValue();

        int avgResultTeam1 = (player1team1 + player2team1 + player3team1 + player4team1 + player5team1) / 5;

        int avgResultTeam2 = (player1team2 + player2team2 + player3team2 + player4team2 + player5team2) / 5;

        if (avgResultTeam1 > avgResultTeam2) {
            System.out.println("Победила команда " + team1 + " набравшая " + avgResultTeam1 + " очков");
        } else {
            System.out.println("Победила команда " + team2 + " набравшая " + avgResultTeam2 + " очков");
        }

        scanner.close();

    }

    public static int getValue(){
        Scanner scanner = new Scanner(System.in);
        int value=scanner.nextInt();

        return value;
    }
}
13
  • я такую структуру ещё не выучил, а как через nextLine? :)))))
    – Dead356
    7 июл 2022 в 18:02
  • Можно убрать тогда try - catch блоки и просто считывать цифры командой player1team1 = scanner.nextInt(); Только при этом при вводе букв вместо цифр - у вас программа будет завершаться с ошибкой, оно же исключение InputMismatchException
    – had0uken
    7 июл 2022 в 18:04
  • а как метод сделать чтобы не повторялись if из этого? чтобы не прописывать каждый раз if?
    – Dead356
    7 июл 2022 в 18:05
  • if (scanner.hasNext()) { System.out.println("You put the wrong value! "); System.exit(0); }
    – Dead356
    7 июл 2022 в 18:07
  • как сделать из этого метод?
    – Dead356
    7 июл 2022 в 18:07

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.