如何将Scanner输入放入数组中...例如一些数字

22
Scanner scan = new Scanner(System.in);
double numbers = scan.nextDouble();
double[] avg =..????

这是已知数量还是未知数量的条目? - Bozho
13个回答

28

你可以尝试像这样做:

public static void main (String[] args)
{
    Scanner input = new Scanner(System.in);
    double[] numbers = new double[5];

    for (int i = 0; i < numbers.length; i++)
    {
        System.out.println("Please enter number");
        numbers[i] = input.nextDouble();
    }
}

除非我误解了您的意思,否则这似乎是相当基础的东西。


当你超过数组容量(5)时,这种方法将无法工作。更好的选择是使用List。 - Mark Hughes
@MarkHughes:确实如此,但是楼主要求一个数组。 - npinti
这就是为什么我将其留作评论而不是答案。这些问题通常会出现在搜索结果中 :) - Mark Hughes

9
您可以使用以下代码获取所有的双倍数:
List<Double> numbers = new ArrayList<Double>();
while (scan.hasNextDouble()) {
    numbers.add(scan.nextDouble());
}

我们如何将字符串添加到List中?我使用了这段代码while(scanner.hasNext()){ list.add(scanner.next().toString());}但是它给了我一个NullPointerException - Kasun Siyambalapitiya

3
**Simple solution**
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int size;
    System.out.println("Enter the number of size of array");
    size = sc.nextInt();
    int[] a = new int[size];
    System.out.println("Enter the array element");
    //For reading the element
    for(int i=0;i<size;i++) {
        a[i] = sc.nextInt();
    }
    //For print the array element
    for(int i : a) {
        System.out.print(i+" ,");
    }
}

2
代码总是很好的,但也有助于提供一些关于你的解决方案如何解决原始问题的评论。这是进一步改进此次和未来答案的建议。 - craigcaulfield
谢谢,现在写得好了吗?还是有其他格式问题?再次感谢。 - Sonu patel

3
import java.util.Scanner;

public class Main {
    /**
     * @param args
     */
    public static void main(String[] args) {
        Scanner in=new Scanner (System.in);
        int num[]=new int[10];
        int average=0;
        int i=0;
        int sum=0;

        for (i=0;i<num.length;i++) {
            System.out.println("enter a number");
            num[i]=in.nextInt();
            sum=sum+num[i];
        }
        average=sum/10;
        System.out.println("Average="+average);
    }
}

这可以用来获取输入的平均值。 - Kasun Siyambalapitiya

2

如果你有一个由空格分隔的数组值" ",你可以尝试这个酷炫的一行Java 8及以上版本支持的流解决方案:

Scanner scan = new Scanner(System.in);
double[] arr = Arrays.stream(scan.nextLine()
                                  .trim()
                                  .split(" "))
                                  .filter(x -> !x.equals(""))
                                  .mapToDouble(Double::parseDouble)
                                  .toArray();

对于整数数组,您可以尝试以下方法:

 Scanner scan = new Scanner(System.in);
 int[] arr = Arrays.stream(scan.nextLine()
                                  .trim()
                                  .split(" "))
                                  .filter(x -> !x.equals(""))
                                  .mapToInt(Integer::parseInt)
                                  .toArray();

使用filter()方法,您还可以避免输入之间的多个空格。

完整的代码参考:

import java.util.Scanner;
import java.util.Arrays;

public class Main{  
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        double[] arr = Arrays.stream(scan.nextLine()
                                    .trim()
                                    .split(" "))
                                    .filter(x -> !x.equals(""))
                                    .mapToDouble(Double::parseDouble)
                                    .toArray();
                              
        for(double each: arr){
            System.out.print(each + "  ");
        }
    }
 }

输入:1 2 3 4 5 6 7 8 9

输出:1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0

如果您仔细观察,输入中有随机的额外空格,这也通过使用.filter(x -> !x.equals(""))进行处理,以避免空白输入("")。


1
你能否发布整个代码片段,包括Scanner类的实例化、正确的导入以及结果的呈现? - JacobTheKnitter
@JacobTheKnitter,我已经添加了代码解释以便更好地理解。 - Ayush Choudhary

1
import  java.util.Scanner;

class Array {
public static void main(String a[]){

    Scanner input = new Scanner(System.in);

    System.out.println("Enter the size of an Array");

    int num = input.nextInt();

    System.out.println("Enter the Element "+num+" of an Array");

    double[] numbers = new double[num];

    for (int i = 0; i < numbers.length; i++)
    {

        System.out.println("Please enter number");

        numbers[i] = input.nextDouble();

    }

    for (int i = 0; i < numbers.length; i++)
    {

        if ( (i%3) !=0){

            System.out.print("");

            System.out.print(numbers[i]+"\t");

        } else {
            System.out.println("");

            System.out.print(numbers[i]+"\t");
        }

    }

}

0

这是一个程序,展示如何从系统中获取输入,并计算每个级别的总和和平均值。

package NumericTest;

import java.util.Scanner;

public class SumAvg {


 public static void main(String[] args) {

 int i,n;
 System.out.println("Enter the number of inputs");
 Scanner sc = new Scanner(System.in);
 n=sc.nextInt();
 int a[] = new int [n];

    System.out.println("Enter the inputs");
   for(i=0;i<n;i++){
   a[i] = sc.nextInt();
  System.out.println("Inputs are " +a[i]);
 }

  int sum = 0;
  for(i=0;i<n;i++){
 sum = sum +a[i];
  System.out.println("Sums : " +sum);
 }
  int avg ;
  avg = sum/n;
  System.out.println("avg : " +avg);
  }
 }

0

如果您不知道数组的大小,需要定义何时停止读取序列(在下面的示例中,程序在用户输入0时停止,显然,最后一个零不应计入其中)。

import java.util.Scanner;
import java.util.ArrayList;

public class Main
{

  public static void main (String[]args)
  {
        
        System.out.println("Introduce the sequence of numbers to store in array. Each of the introduced number should be separated by ENTER key. Once you're done, type in 0.");
        Scanner scanner = new Scanner(System.in);
        ArrayList<Integer> numbers = new ArrayList<Integer>();
        boolean go = true; 
        while (go) {
            int value = scanner.nextInt();
            numbers.add(value);
            if (value == 0) {
                go = false;
                numbers.remove(numbers.size() - 1);
            }
        }
        System.out.println(numbers);
  }
}

0
double [] avg = new double[5];
for(int i=0; i<5; i++)
   avg[i] = scan.nextDouble();

0
List<Double> numbers = new ArrayList<Double>();
double sum = 0;

Scanner scan = new Scanner(System.in);
while(scan.hasNext()){
    double value = scan.nextDouble();
    numbers.add(value);
    sum += value;
}

double average = sum / numbers.size();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接