循环使用Java代码的问题

时间:2015-10-27 12:14:07

标签: java loops if-statement while-loop

  

使用while循环不断询问用户输入的顺序   直到用户确实以正确的顺序给出两个数字(第一个   小于第二

嗨!我是java的初学者,我有这个代码,但我无法循环“错误”消息。它只打印2次

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

2 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分: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.");
    }
}