简体   繁体   中英

How can I print numbers between two numbers that I enter?

I am creating a program which asks the user to enter two numbers. It will then print the numbers the user entered and the numbers between the two numbers in numerical order. I declared and initialized two variables, which are 'number1' and 'number2'.

    int number1;
    int number2;
    do{
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the first number: " );
        number1 = input.nextInt();
    
        System.out.print("Enter the second number: " );
        number2 = input.nextInt();
    
        if(number1 == number2)
        {
           System.out.println("The numbers you entered equal with each other. Try again.\n");
        }
    }while(number1 == number2);

    if (number1 > number2)
    {
        for(int a = number2; a <= number1; a++)
        {
            System.out.print(a + " ");
        }
    }
    
    else
    {
        for(int a = number1; a <= number2; a++)
        {
            System.out.print(a + " ");
        }
    } 

How do I make it so it also prints only the numbers between 'number1' and 'number2'?

The first part of your code was fine, if you want to do it this way.

    Scanner scanner = new Scanner(System.in);
    int first, second;

    do {
        System.out.print("Enter the first number: ");
        first = scanner.nextInt();
        System.out.print("Enter the second number: ");
        second = scanner.nextInt();

        if (first == second) {
            System.out.println("The numbers you entered equal with each other. Try again.\n");
        }
    } while (first == second);

For the second part, I'd recommend determining which number is which (smaller/bigger) instead of using duplicate code. Also you need to only cycle through numbers in between the numbers you chose, so you have to change your for cycle

  //determine which number is bigger/smaller
  int smaller = Math.min(first, second);
  int bigger = Math.max(first, second);

  for(int i = smaller+1 ; i < bigger ; i++){
      System.out.print(i + " ");
  }

The only odd scenario here is where you input two numbers which are adjacent, which will output no numbers. For example 3 and 4.

int max = Math.max(number1, number2); for(int i = (max == number1 ? number2 : number1) + 1 ; i < max ; i++) { System.out.println(i); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM