Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Scanning in line of integers into arraylist (or array)

$
0
0
What I'm trying to do is read a line of 4 integers from the standard input. Integers will be entered like so: 100 20 30 20.

I've tried to do this using a normal array, but it did not work. I would enter the four integers, but nothing would happen when I pressed enter. So I tried using the arraylist class as so:

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


public class Internship {
	public static void main(String[] args){
		//int[] lotteryInput = new int[4];
		ArrayList<Integer> lotteryInput = new ArrayList<Integer>(4);
		Scanner scan = new Scanner(System.in);
		for(int i = 0; i < lotteryInput.size() ; i++){
			while(scan.hasNextInt()){
				lotteryInput.set(i, scan.nextInt());
			}
			
			
		}
		
	
	}

}



This does not work. The scanner isn't even scanning for any thing. Here's my regular array code:

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


public class Internship {
	public static void main(String[] args){
		//int[] lotteryInput = new int[4];
		int[] lotteryInput = new int[4];
		Scanner scan = new Scanner(System.in);
		for(int i = 0; i < lotteryInput.length ; i++){
			while(scan.hasNextInt()){
				lotteryInput[i] = scan.nextInt();
			}
			
			
		}
		System.out.println(lotteryInput);
		
	
	}

}



Any help would be much appreciated.

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>