【问题标题】:Issue with looping in Java codeJava代码中的循环问题
【发布时间】:2015-10-27 12:14:06
【问题描述】:

使用while循环不断要求用户输入顺序 数字,直到用户确实以正确的顺序给出了两个数字(首先 小于秒

嗨!我是java的初学者,我有这个代码,但我不能循环“错误”消息。它只打印了 2 次​​p>

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

【问题讨论】:

  • 您能否让人们知道您使用了哪些输入?
  • 你的实际问题是什么,对我来说它正在工作。
  • 你需要另一个循环,if/else 子句在其中。
  • 嗨,这是我输入的内容:请输入两个数字:3 1 错误:第一个数字必须小于第二个数字 请输入两个数字:6 1
  • 一个简单的解决方案是将while(num1 &lt; num2) { // display error and ask again } 放在开头,然后打印计数器循环。

标签: java loops if-statement while-loop


【解决方案1】:
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();
}

【讨论】:

    【解决方案2】:
    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.");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-08
      • 1970-01-01
      • 2022-12-06
      • 1970-01-01
      • 2013-04-07
      • 2011-07-03
      • 1970-01-01
      相关资源
      最近更新 更多