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

强颜欢笑 提交于 2019-12-01 07:38:50

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'.

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
import java.util.*;
class SimpleArrayList{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
ArrayList <Integer> al2 = new ArrayList<Integer>();
System.out.println("enter the item in list");
while(sc.hasNextInt())
{
al2.add(sc.nextInt());
}
Iterator it1 = al2.iterator();
/*loop will be terminated when it will not get integer value */
     while(it1.hasNext())
{
 System.out.println(it1.next());
}
}
}

This is one of the simple and easiest way to use Scanner and ArrayList together.

import java.util.*;
public class Main
{
public static void main(String args[])
{
    Scanner sc=new Scanner(System.in);
    int num=sc.nextInt();
    ArrayList<Integer> list=new ArrayList<Integer>(num);
    for(int i=0;i<num;i++)
    {
    list.add(sc.nextInt());

   }
    Iterator itr=list.iterator();
        {
       while(itr.hasNext())
       {
           System.out.print(itr.next()+" ");
        }
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!