如何使扫描仪理解我写的金额?

时间:2019-07-02 08:02:51

标签: java java.util.scanner

这只是一些家庭作业,但是我找不到想要的方式来实现它。请看一下我的代码。 键入数字后,我想和他们一起玩。

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    //user says if he'd like to use 3 numbers for instance (2,4,5)
    System.out.println("How many numbers would you like to use? : ");
    int amountOfNumbers = sc.nextInt();
    System.out.println("Great! Please type in your numbers: ");
    int numbers =sc.nextInt(amountOfNumbers);
    // should let him write the amount of numbers he entered    
}

一旦他输入了他想使用的数字,我希望扫描仪可以让他输入所有这些数字。

让我们说他想使用的数字数量是3。 我希望他能够在控制台中这样输入:

  • 第一个数字+输入键
  • 第二个数字+输入键
  • 第三个数字+输入键
  • 无法再写

这就是我在扫描仪本身中添加“ amountOfNumbers”的意思……(不起作用)

int numbers =sc.nextInt(amountOfNumbers);

BR

2 个答案:

答案 0 :(得分:2)

考虑一个for循环:

for(int i = 0; i < amountofNumbers; i++){
    // add to a collection / array / list
}

然后从那里访问所需的内容。

答案 1 :(得分:0)

import java.util.*; 
class EnterNumber{

    public void enter_list_function(){

        Scanner sc = new Scanner(System.in);

        System.out.println("How many numbers would you like to use?"); 

        //Enter the Numbers of amount
        int input = sc.nextInt();
        ArrayList<Integer> list = new ArrayList<Integer>();

        System.out.println("Great! Please type in your numbers: "); 
        //Input - Numbers of amount
        for(int j =1; j<=input; j++ ){
            int addval = sc.nextInt();
            //Add the enter amount in array
            list.add(addval);

        }

        Iterator itr=list.iterator();  
        while(itr.hasNext()){  
           //get the enter amount from list
           System.out.println(itr.next());  
        }  
    }


    public static void main(String[] args){

        EnterNumber EnterNumber = new EnterNumber();
        EnterNumber.enter_list_function();

    }

}