Home > other >  Problems checking user-grabbed values in while loops (only else block works)
Problems checking user-grabbed values in while loops (only else block works)

Time:08-02

I have a problem validating the error messages of the two while, when I fill in the right values the loop ends, when I enter incorrect values or leave blank nothing happens. Only what works is the else in each loop.

         while (true){
            try {
                System.out.print("Enter the year of manufacture of the motorcycle: ");
                m1.setYear(keyboard.nextInt());
                if (m1.getYear() <= 0){
                    System.out.println("Year field cannot be less than or equal to zero, redo the operation.");
                } else {
                    break;
                }
            } catch (Exception e) {
                System.out.println("Field must contain only integers, redo the operation.");
            }
        }
        while (true){
            try {
                System.out.print("Enter the value of the motorcycle: ");
                m1.setValue(keyboard.nextDouble());
                if (m1.getValue() <= 0){
                    System.out.println("Value field cannot be less than or equal to zero, redo the operation.");
                } else {
                    break;
                }
            } catch (Exception e) {
                System.out.println("Field must contain only decimal numbers, redo the operation.");
            }
        }

CodePudding user response:

Try using nextLine instead of nextInt/nextDouble:

    while (true){
        try {
            System.out.print("Enter the year of manufacture of the motorcycle: ");
            m1.setYear(Integer.parseInt(keyboard.nextLine()));
            if (m1.getYear() <= 0){
                System.out.println("Year field cannot be less than or equal to zero, redo the operation.");
            } else {
                break;
            }
        } catch (Exception e) {
            System.out.println("Field must contain only integers, redo the operation.");
        }
    }
    while (true){
        try {
            System.out.print("Enter the value of the motorcycle: ");
            m1.setValue(Double.parseDouble(keyboard.nextLine()));
            if (m1.getValue() <= 0){
                System.out.println("Value field cannot be less than or equal to zero, redo the operation.");
            } else {
                break;
            }
        } catch (Exception e) {
            System.out.println("Field must contain only decimal numbers, redo the operation.");
        }
    }
  •  Tags:  
  • java
  • Related