wam090
wam090

Reputation: 2873

How to put a Scanner input into an array... for example a couple of numbers

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

Upvotes: 22

Views: 479634

Answers (13)

Ayush Choudhary
Ayush Choudhary

Reputation: 341

For the values of the array given by separated with space " " you can try this cool one liner Java 8 & onwards suppported streams based solution:

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

For int array you can try:

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

With filter() method you can also avoid more than one spaces in between the inputs.

Complete code reference:

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 + "  ");
        }
    }
 }

Input: 1 2 3 4 5 6 7 8 9

Output: 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0

If you observe carefully, there are extra spaces in between the input randomly, that has also been handled with line .filter(x -> !x.equals("")) so as to avoid blank inputs ("")

Upvotes: 3

JacobTheKnitter
JacobTheKnitter

Reputation: 483

If you don't know the size of the array, you need to define, when to stop reading the sequence (In the below example, program stops when the user introduces 0 and obviously, last zero shouldn't be taken into account).

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);
  }
}

Upvotes: 0

Rohit Mittal
Rohit Mittal

Reputation: 64

public static void main (String[] args)
{
    Scanner s = new Scanner(System.in);
    System.out.println("Please enter size of an array");
    int n=s.nextInt();
    double arr[] = new double[n];
    System.out.println("Please enter elements of array:");
    for (int i=0; i<n; i++)
    {
        arr[i] = s.nextDouble();
    }
}

Upvotes: 0

Harsha pps
Harsha pps

Reputation: 2198

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();

Upvotes: 0

Sonu patel
Sonu patel

Reputation: 339

**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+" ,");
    }
}

Upvotes: 3

UDID
UDID

Reputation: 2423

This is a program to show how to give input from system and also calculate sum at each level and average.

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);
  }
 }

Upvotes: 0

Vishal Kushwah
Vishal Kushwah

Reputation: 1

import java.util.Scanner;
public class sort {

  public static void main(String args[])
    {
        int i,n,t;          

        Scanner sc=new Scanner(System.in);

        System.out.print("Enter the size of array");

        n=sc.nextInt();

        int a[] = new int[n];

        System.out.println("Enter elements in array");

        for(i=0;i<n;i++)
        {
            a[i]=sc.nextInt();
        }
        t=a[1];

        for(i=0;i<n;i++)
        {
            if(a[i]>t)

                t=a[i];
        }
        System.out.println("Greates integer is" +t);
    }
}

Upvotes: -1

ASHISH RANJAN
ASHISH RANJAN

Reputation: 61

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");
        }

    }

}

Upvotes: 1

alrashdi
alrashdi

Reputation: 1

Scanner scan = new Scanner (System.in);

for (int i=0; i<=4, i++){

    System.out.printf("Enter value at index"+i+" :");

    anArray[i]=scan.nextInt();

}

Upvotes: -1

Jossel M. Barnobal
Jossel M. Barnobal

Reputation: 31

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);
    }
}

Upvotes: 3

npinti
npinti

Reputation: 52185

You could try something like this:

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();
    }
}

It seems pretty basic stuff unless I am misunderstanding you

Upvotes: 28

Felipe Cypriano
Felipe Cypriano

Reputation: 2737

You can get all the doubles with this code:

List<Double> numbers = new ArrayList<Double>();
while (scan.hasNextDouble()) {
    numbers.add(scan.nextDouble());
}

Upvotes: 9

Feyyaz
Feyyaz

Reputation: 3206

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

Upvotes: 0

Related Questions