繁体   English   中英

如何让ArrayList <Integer>和Scanner玩得很好?

[英]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]);
      }   
}

由于糟糕的调试,我发现while(scan.hasNextInt())实际上并没有添加任何内容。 可能出了什么问题? 我的谷歌软弱还是缺乏让我失望的技术诀窍? 我对编程很陌生,所以不熟悉Lists所以认为这将是一个不错的第一步,但有些东西并没有增加。 它也编译好,所以它不是语法(不再)。 也许铸造问题?

你的问题在这里:

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

只需在输入所有整数值后输入一个字符,例如q ,然后程序将打印预期结果。

Sample Input :14 17 18 33 54 1 4 6 q

这是否有效,掌握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]);
    }
  }   
}

我假设您需要将列表作为数组,否则无需转换为数组。 正如Jon Skeet在评论中提到的,循环将仅在流没有下一个int时终止,即。 如果您正在使用'java CyclicShiftApp <input_file.txt',则为非整数值或文件的EOF。

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

这是一起使用Scanner和ArrayList的简单且最简单的方法之一。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM