java 如何使用扫描仪将值读入数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27810955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 12:26:02  来源:igfitidea点击:

How to read in a value into an array using Scanner

javaarraysjava.util.scanner

提问by deSynthesize

I don't have any code to show what I am trying to do, because I honestly have no ideahow to approach this.

我没有任何代码来显示我想要做什么,因为老实说我不知道如何处理这个问题。

What I am trying to do is have the user input how many numbers will be into an array. So basically, this is what I would like to be the output:

我想要做的是让用户输入数组中将包含多少个数字。所以基本上,这就是我想要的输出:

How many students in the class? 3

Enter the marks: 76 68 83

The class average is 75.67 %

班上有多少学生?3

输入分数:76 68 83

班级平均为 75.67 %

I can program everything else, except for the first line. I have no idea how to read in a number into an array, so that the array will be as big as that number.

除了第一行之外,我可以对其他所有内容进行编程。我不知道如何将数字读入数组,以便数组与该数字一样大。

Thank you.

谢谢你。

回答by James C. Taylor IV

To start you will need to set up your scanner to read console input:

首先,您需要设置扫描仪以读取控制台输入:

Scanner scanner = new Scanner(System.in);

You can then use function such as scanner.next()or scanner.nextInt()to get the input from the console. Hopefully this gives you some idea of where to start. If you need to look up more Scanner functions check the Scanner Documentation

然后,您可以使用诸如scanner.next()或 之类的函数scanner.nextInt()从控制台获取输入。希望这能让你知道从哪里开始。如果您需要查找更多扫描仪功能,请查看扫描仪文档

As far as arrays go you simply need to save the first int input to the console and use this for size:

就数组而言,您只需将第一个 int 输入保存到控制台并使用它的大小:

int size = Integer.parseInt(scanner.next());
int[] array = new int[size];

Then you should be able to use a loop to save each individual score.

然后您应该能够使用循环来保存每个单独的分数。

回答by Abhishek Kumar

 import java.util.Scanner; 

 public class TestArrayInputViaConsole {
   public static void main(String args[]) {
     double sum = 0;
     double avg = 0;
     Scanner sc = new Scanner(System.in);
     System.out.println("Enter how many students are in the class? ");
     int ArraySize = sc.nextInt();
     int[] marks = new int[ArraySize];
     System.out.println("Enter the marks:");

     for(int i = 0; i < ArraySize; i++) {
       marks[i] = sc.nextInt();
       sum = sum + marks[i]; 
     }

     avg = (sum / ArraySize);
     System.out.println("Average of the class : " + avg);    
   } 
 }