0

Use a while loop to keep asking the user to enter the order of numbers until the user does give two numbers in the right order (first smaller than second

Hi! i'm a beginner in java and I have this code but I can't loop the "error" message. it just prints 2 times

import java.util.Scanner;

public class Q6 {
    public static void main(String[] args) {
        int num1, num2;
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Please type two numbers:");
        num1 = keyboard.nextInt();
        num2 = keyboard.nextInt();

        if (num1 < num2) {
            int counter = num1;
            while (counter <= num2) {
                System.out.print(counter + " ");
                counter = counter + 1;
            }
        } 
        else {
            System.out.println("Error: the first number must be smaller than the second");
            System.out.print("Please type two numbers: ");
            num1 = keyboard.nextInt();
            num2 = keyboard.nextInt();
        }
    }
}
5
  • 1
    Could you perhaps let people know which inputs you used? Commented Oct 27, 2015 at 12:15
  • 1
    what´s your actuall problem, for me it is working. Commented Oct 27, 2015 at 12:15
  • 1
    You need another loop, in which the if/else clause goes. Commented Oct 27, 2015 at 12:16
  • Hi, here's what I entered: Please type two numbers:3 1 Error: the first number must be smaller than the second Please type two numbers: 6 1 Commented Oct 27, 2015 at 12:16
  • An easy solution is to put while(num1 < num2) { // display error and ask again } in the beginning and after that print the counter loop. Commented Oct 27, 2015 at 12:22

2 Answers 2

2
int num1,num2;
while (num1>=num2) {
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Please type two numbers");
    System.out.printn("first number must be smaller than the second:)";
    num1 = keyboard.nextInt();
    num2 = keyboard.nextInt();
}
Sign up to request clarification or add additional context in comments.

Comments

1
int num1,num2;
while (num1>=num2) {
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Please type two numbers:");
    num1 = keyboard.nextInt();
    num2 = keyboard.nextInt();
    if(num1>=num2) {
         System.out.println("Error: First number must be smaller than the second.");
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.