How to enter two numbers and print out the numbers

2019-06-09 09:13发布

I was wondering how to ask the user to input two numbers and show the numbers in between those like a range I guess. For an example I'm suppose to have a high and low variable where you enter two numbers between 1-300 and the user would type in say 15 and 30 and have it print out 15,16,17...to 30. Its suppose to be a program that does conversion with decimals with a bunch of for loops and while loops in it. I feel like I'm starting to get discourage with this stuff and my teacher is knowledgeable with Java but I feel like he's rushing us because he hands out assignments for chapters we haven't covered in class and we won't for another two weeks. thanks

3条回答
爷、活的狠高调
2楼-- · 2019-06-09 09:35

By your description, it sounds like you want to print out integers from some value k to another value n.

k, k+1, k+2, ..., n-1, n

Use input dialogs or Scanner and System.in to gather inputs. Clip the inputs to the min and max of a desired range.

if k < min
    input = min
else if input > max
    n = max

Next, set the lower value to be the starting value. Then, print out each number until max.

for (int i = k; i <= n; i++)
    print i
查看更多
何必那么认真
3楼-- · 2019-06-09 09:45

Simple algorithm for getting this done, would be:

 public static void main(String[] args) {
        System.out.print("Min:");
        Scanner scanner = new Scanner(System.in);
        int min = scanner.nextInt();
        System.out.println(min+" read in as Min");
        System.out.print("Max:");
        int max = scanner.nextInt();
        System.out.println(min+" read in as Max");
        for (;min<=max; min++) {
            System.out.println(min);
        }
    }

There's nothing with pushing you, as there no magic in this assignment. Please google a bit, as this can bea eassily found on SO, and asking answered questions can get you in trouble

查看更多
The star\"
4楼-- · 2019-06-09 10:00

The following code will ask for a minimum, maximum, and then print each integer between the two. This might help you get started:

import java.util.Scanner;
public class RangePrinter {
    public static void main(String[] args) {

        // screate a scanner instance for user input
        Scanner reader = new Scanner(System.in);

        System.out.println("Enter the first number");

        // get user input for min range
        int min=reader.nextInt();

        System.out.println("Enter a second number");

        // get user input for max range
        int max=reader.nextInt();

        for (int i=min; i < max + 1; i++)
        {
            System.out.println(i);
        }

   }
}
查看更多
登录 后发表回答