Мое время l oop in java не работает и завершает его только один раз - PullRequest
1 голос
/ 07 апреля 2020

Это будет только go через один раз, поэтому оно будет заканчиваться словами «Хотите сделать еще один запрос? (Y / n)», а когда я введу «y», оно останавливается и не будет выполнять l oop.

package Chaterp5PPReynaGuerra;
import java.util.*;
public class MeetingRequest 
{

    public static void main(String[] args) 
    {

        Scanner scan = new Scanner(System.in);

        final int CAPACITY=30;
        String name;
        int people;
        int morePeople;
        String answer="y";
        int fewerPeople;

        System.out.println("--------Meeting Request System"+
        "--------");

        System.out.println("\nWelcome to the Meeting Request System."+
        " May I know your name?");
        name=scan.nextLine();


        while(answer.equalsIgnoreCase("y")) 
        {
            System.out.println("Hello, "+name+", how many people"+
                    " will be attending the meeting?");
                    people=scan.nextInt();

                    morePeople = CAPACITY - people;
                if(people < CAPACITY)
                    System.out.println("You can invite "+morePeople+
                    " more people to the meeting.");
                else if(people > CAPACITY) {
                    fewerPeople= people - CAPACITY;
                         System.out.println("Sorry, the room is not "+
                "big enough to seat that many people. You have to "+
                     "exclude "+fewerPeople+" from the meeting.");
                    }
            System.out.println();

            System.out.println("Would you like to make another"+
            " request?(y /n)");
            // gets rid of \n in the input stream
            scan.next();
            answer=scan.nextLine();
        }



    }

}

Ответы [ 2 ]

0 голосов
/ 07 апреля 2020

Замените

people=scan.nextInt();

на

people = Integer.parseInt(scan.nextLine());

Проверка Сканер пропускает nextLine () после использования next () или nextFoo ()? , чтобы узнать больше о it.

Ниже приводится исправленная программа:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        final int CAPACITY = 30;
        String name;
        int people = 0;
        int morePeople;
        String answer = "y";
        int fewerPeople;
        boolean valid;
        System.out.println("--------Meeting Request System" + "--------");

        System.out.println("\nWelcome to the Meeting Request System." + " May I know your name?");
        name = scan.nextLine();

        do {
            do {
                valid = true;
                System.out.println("Hello, " + name + ", how many people" + " will be attending the meeting?");
                try {
                    people = Integer.parseInt(scan.nextLine());
                } catch (NumberFormatException e) {
                    System.out.println("Invalid entry. Pleaase try again.");
                    valid = false;
                }
            } while (!valid);

            morePeople = CAPACITY - people;
            if (people < CAPACITY)
                System.out.println("You can invite " + morePeople + " more people to the meeting.");
            else if (people > CAPACITY) {
                fewerPeople = people - CAPACITY;
                System.out.println("Sorry, the room is not " + "big enough to seat that many people. You have to "
                        + "exclude " + fewerPeople + " from the meeting.");
            }
            System.out.println();

            System.out.println("Would you like to make another" + " request?(y /n)");
            answer = scan.nextLine();
        } while (answer.equalsIgnoreCase("y"));
    }
}

Пример выполнения:

--------Meeting Request System--------

Welcome to the Meeting Request System. May I know your name?
abc
Hello, abc, how many people will be attending the meeting?
x
Invalid entry. Pleaase try again.
Hello, abc, how many people will be attending the meeting?
10.4
Invalid entry. Pleaase try again.
Hello, abc, how many people will be attending the meeting?
4
You can invite 26 more people to the meeting.

Would you like to make another request?(y /n)
y
Hello, abc, how many people will be attending the meeting?
5
You can invite 25 more people to the meeting.

Would you like to make another request?(y /n)
n

Некоторые другие важные моменты:

  1. Как видите, do...while l oop более подходит вместо while l oop в этом случае.
  2. Вы всегда должны проверять NumberFormatException когда вы анализируете текст (например, Scanner::nextLine()) в целое число.

Не стесняйтесь комментировать в случае каких-либо сомнений / проблем.

0 голосов
/ 07 апреля 2020

Использование next() вернет только то, что находится перед разделителем (по умолчанию используется пробел). nextLine() автоматически перемещает сканер вниз после возврата текущей строки.

Чтобы избавиться от \ n, используйте scan.nextLine

// gets rid of \n in the input stream
            scan.nextLine();
            answer=scan.nextLine();

Надеюсь, эта помощь.

...