gpt4 book ai didi

java - Java 代码中的循环问题

转载 作者:行者123 更新时间:2023-12-01 22:03:05 26 4
gpt4 key购买 nike

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

嗨!我是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();
}
}
}

最佳答案

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

关于java - Java 代码中的循环问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33367732/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com