Write a program to read two numbers, the first less than the second. The program will write all numbers between the two numbers

StackOverflow https://stackoverflow.com/questions/19528826

문제

//So I wrote this: (the output down there)

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.

//so many number 4 repeating can someone tell me where am i wrong? thanks!!

도움이 되었습니까?

해결책 2

  while(num1<=num2){
   int counter=num1;
   System.out.print(counter+" "+num2);
   counter=counter+1;
  }

This will end up in infinite loop. The condition for the while loop needs to be modified.

// modified code - Complete code.

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

다른 팁

int counter=num1;

You created a new counter variable for each iteration of the loop.
Therefore, they all have the same value.

It runs forever because your loop condition can never be false (you never change num1 or num2).

As a novice programmer I would use for loop instead. It would be simpler and easier:

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

Here you go:

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++;
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top