如何获得的ArrayList<整数GT;和扫描仪发挥好? [英] How to get ArrayList<Integer> and Scanner to play nice?

查看:83
本文介绍了如何获得的ArrayList<整数GT;和扫描仪发挥好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

由于穷人芒调试我发现,在而(scan.hasNextInt())心不是实际添加任何东西。可能是什么回事?是我的谷歌富薄弱或缺乏知识的让我失望?我是相当新的节目,并因此认为这将是一个很好的第一步,但心不是东西加起来列出那么的陌生。它还编译正常所以它不是语法(了)。也许是铸造的问题?

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?

推荐答案

这是否工作,掌握Samwise?

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

我假设有就是为什么你需要在列表作为一个数组的理由,否则转换到一个数组是不必要的。如乔恩斯基特评价提及,当该流不具有下一个整型,即循环将仅终止。一个非整数值,或者如果你使用公司的Java CyclicShiftApp℃的文件的EOF; input_file.txt。

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

这篇关于如何获得的ArrayList&LT;整数GT;和扫描仪发挥好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆