如何获取 ArrayList<Integer>和扫描仪玩的好吗? [英] How to get ArrayList&lt;Integer&gt; and Scanner to play nice?

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

问题描述

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

感谢poor-mans-debugging,我发现while(scan.hasNextInt()) 实际上并没有添加任何东西.可能出什么问题了?是我的 google-fu 弱还是缺乏专业知识让我失望?我对编程很陌生,所以不熟悉列表,所以认为这将是一个不错的第一步,但并没有增加一些东西.它也编译得很好,所以它不是语法(不再).也许是铸造问题?

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

我假设您需要将列表作为数组是有原因的,否则不需要转换为数组.正如 Jon Skeet 在评论中提到的,只有当流没有下一个 int 时,循环才会终止,即.如果您使用的是java CyclicShiftApp <",则为非整数值或文件的 EOFinput_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<Integer>和扫描仪玩的好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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