【问题标题】:Write a program to read two numbers, the first less than the second. The program will write all numbers between the two numbers编写程序读取两个数字,第一个小于第二个。该程序将写入两个数字之间的所有数字
【发布时间】:2013-10-22 21:35:45
【问题描述】:

//所以我写了这个:(下面的输出)

import java.util.Scanner;
public class E7L6{
public static void main(String[]args){
int num1, num2;
Scanner keyboard= new Scanner(System.in);
System.out.print("Type two numbers:");
num1= keyboard.nextInt();
num2= keyboard.nextInt();

if(num1<num2){
   while(num1<=num2){
   int counter=num1;
   System.out.print(counter+" "+num2);
   counter=counter+1;
   }}
else{
   System.out.print("Error: the first number must be smaller than the second");
}   
  }}

Output:
 ----jGRASP exec: java E7L6
Type two numbers:4 124
 4 4 4 4 4 4 4 4 4
 ----jGRASP: process ended by user.

//这么多数字 4 重复有人能告诉我我哪里错了吗?谢谢!!

【问题讨论】:

  • 同样的问题——你所做的只是乞求答案。嘘。

标签: java while-loop counter jgrasp


【解决方案1】:
int counter=num1;

您为循环的每次迭代创建了一个新的 counter 变量。
因此,它们都具有相同的值。

它永远运行,因为你的循环条件永远不会是假的(你永远不会改变 num1num2)。

【讨论】:

  • 我修改它以将 int 计数器放在首位,我现在有一个数字序列但仍然永远运行,(1 10) 不会在 10 处停止它会继续吗?
  • @BaderK:正如我在回答末尾所说,您需要更改循环,以便它知道何时停止。
【解决方案2】:
  while(num1<=num2){
   int counter=num1;
   System.out.print(counter+" "+num2);
   counter=counter+1;
  }

这将进入无限循环。需要修改while循环的条件。

//修改后的代码——完整的代码。

import java.util.Scanner;

public class E7L6 {
    public static void main(String[] args) {
        int num1, num2;
        Scanner keyboard = new Scanner(System.in);
        System.out.print("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
                    .print("Error: the first number must be smaller than the second");
        }
    }
}

【讨论】:

  • 谢谢!我现在有一个数字序列,但不限于 num2(例如 4 10)它不会停在 10
  • 我在这里更新了完整的代码。它为我工作。只需与您的代码进行比较即可。
  • @GreenShadow:请不要为人们做作业。相反,解释问题是什么,让他们自己想办法解决。否则,你就违背了作业的目的。
  • @GreenShadow:是的,他刚刚删除了他最近的问题,但是你教他的只是如何乞讨。
【解决方案3】:

作为一个新手程序员,我会改用 for 循环。它会更简单,更容易:

for(ctr=num1;ctr<=num2;ctr++)
   s.o.p(ctr)

【讨论】:

    【解决方案4】:

    给你:

    System.out.print("First:");
        int first = Integer.parseInt(reader.nextLine());
        System.out.print("Second:");
        int second = Integer.parseInt(reader.nextLine());
        while (first <= second) {
            System.out.println(first);
            first++;
        }
    

    【讨论】:

      猜你喜欢
      • 2020-11-09
      • 1970-01-01
      • 2020-08-11
      • 1970-01-01
      • 1970-01-01
      • 2022-10-24
      • 2022-11-21
      • 2017-02-13
      • 2021-09-05
      相关资源
      最近更新 更多