Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从文件中读取Int作为对象,然后将其转换回Int-Java_Java_Arrays_Object - Fatal编程技术网

从文件中读取Int作为对象,然后将其转换回Int-Java

从文件中读取Int作为对象,然后将其转换回Int-Java,java,arrays,object,Java,Arrays,Object,我最初不把它读成int的原因是因为我也在读非int字符。 该文件如下所示: 詹姆斯80 戴夫90 Ty 64 我用这个来占据ArrayList: while (scan.hasNext()){ //while end of file not reached n.add(scan.next()); count++; } 但是,当我想使用instanceof从数组中取出整数时,似乎 (n.get(i) instanceof Inte

我最初不把它读成int的原因是因为我也在读非int字符。 该文件如下所示:

詹姆斯80

戴夫90

Ty 64

我用这个来占据ArrayList:

while (scan.hasNext()){ //while end of file not reached
        n.add(scan.next()); 
        count++;            
    }
但是,当我想使用instanceof从数组中取出整数时,似乎

(n.get(i) instanceof Integer)
对于数组中的每个值返回false,即使它已被正确占用,例如

{James, 80, Dave, 90, Ty, 64}
我使用的逻辑是,每个其他对象都是整数,所以

for (int i = 0; i < n.size() ; i++){

        if(n.get(i) instanceof Integer){
    ....
    }
}
for(int i=0;i
这应该让我只过滤出整数,但我的程序没有输入if语句


我的逻辑是否有缺陷,或者我是否需要在将int放入ArrayList之前找到一种收集int的方法,如果有,您能给我一个关于我需要做什么的线索吗?

使用hasNextInt方法似乎已经解决了这个问题

while (scan.hasNext()){ //while end of file not reached
        if(scan.hasNextInt()){
            n.add(scan.nextInt());
        }else{
            n.add(scan.next());
        }

使用hasNextInt方法似乎解决了这个问题

while (scan.hasNext()){ //while end of file not reached
        if(scan.hasNextInt()){
            n.add(scan.nextInt());
        }else{
            n.add(scan.next());
        }

Scanner.next()
返回一个
字符串
,因此它不能是
整数
。对,但在将字符串放入数组之前,我将使用什么逻辑从字符串中预先确定整数?您可以使用
Integer.parseInt(String)
解析输入,也可以使用
Scanner.hasnetint()
Scanner.nextInt()
。如果您将
ArrayList
定义为
ArrayList
,那么您在编译时就已经发现并识别了这个问题。我没有正确解释,但我也想将名称保留在数组中,多亏了@Bubletan.
Scanner.next()
返回一个
字符串
,因此它不能是
整数
。对,但是在将字符串放入数组之前,我应该使用什么逻辑从字符串中预先确定一个整数?您可以使用
Integer.parseInt(String)
解析输入,也可以使用
Scanner.hasNextInt()
Scanner.nextInt()
。如果您将
ArrayList
定义为
ArrayList
,那么您在编译时就已经发现并识别了这个问题。我没有正确解释,但我也想将名称保留在数组中,多亏了@Bubletan,我找到了正确的答案。