Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get ArrayList<Integer> and Scanner to play nice?

import java.util.*;

public class CyclicShiftApp{

   public static void main(String[] args){
      Scanner scan = new Scanner(System.in);
      ArrayList<Integer> list = new ArrayList<Integer>();
      while(scan.hasNextInt()){
         list.add(scan.nextInt());
      }
      Integer[] nums = new  Integer[list.size()];
      nums = list.toArray(nums);
      for(int i = 0;i < nums.length; i++){
      System.out.println(nums[i]);
      }   
}

Thanks to poor-mans-debugging I've found that the while(scan.hasNextInt()) isnt actually adding anything. What might be going wrong? Is my google-fu weak or lack of know-how letting me down? I am rather new to programming, and so unfamiliar with Lists so thought this would be a nice first step but something isnt adding up. It also compiles fine so Its not syntax(anymore). Perhaps a casting issue?

like image 957
Samwise Gibbens Avatar asked Apr 19 '13 05:04

Samwise Gibbens


2 Answers

Does this work, master Samwise?

import java.util.*;

public class CyclicShiftApp{

public static void main(String[] args){
    Scanner scan = new Scanner(System.in);
    ArrayList<Integer> list = new ArrayList<Integer>();
    System.out.print("Enter integers please ");
    System.out.println("(EOF or non-integer to terminate): ");

    while(scan.hasNextInt()){
         list.add(scan.nextInt());
    }

    Integer [] nums = list.toArray(new Integer[0]);
    for(int i = 0; i < nums.length; i++){
       System.out.println(nums[i]);
    }
  }   
}

I'm assuming there's a reason why you need the list as an array, otherwise the conversion to an array is unnecessary. As Jon Skeet mentions in the comments, the loop will terminate only when the stream doesn't have a next int, ie. a non-integer value or a file's EOF if you're using 'java CyclicShiftApp < input_file.txt'.

like image 131
rtheunissen Avatar answered Sep 29 '22 06:09

rtheunissen


Your problem is here :

 while(scan.hasNextInt()){  <-- This will loop untill you enter any non integer value
     list.add(scan.nextInt());
  }

You just have to enter a character say e.g q once you finished entering all the integer values and then your program will print expected results.

Sample Input :14 17 18 33 54 1 4 6 q
like image 40
Amit Deshpande Avatar answered Sep 29 '22 05:09

Amit Deshpande