Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/366.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/eclipse/9.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
在文件中扫描给定的数字-Java_Java_Eclipse_Loops_Io - Fatal编程技术网

在文件中扫描给定的数字-Java

在文件中扫描给定的数字-Java,java,eclipse,loops,io,Java,Eclipse,Loops,Io,我的方法有问题。任务是扫描包含不同数字的文件。我想做一个方法,在文件中扫描数字1到10 问题是while循环从未激活。我不知道这是因为该值从不为真,还是因为方法hasnetint在以这种方式使用时存在问题 为了解决这个方法的问题,我在循环内外使用了print语句 代码: package jr222er_lab4; import java.util.Scanner; import java.io.*; public class Histogram { public static voi

我的方法有问题。任务是扫描包含不同数字的文件。我想做一个方法,在文件中扫描数字1到10

问题是while循环从未激活。我不知道这是因为该值从不为真,还是因为方法hasnetint在以这种方式使用时存在问题

为了解决这个方法的问题,我在循环内外使用了print语句

代码:

package jr222er_lab4;

import java.util.Scanner;
import java.io.*;

public class Histogram {
    public static void main(String[] args) throws IOException{
        File file = new File ("C:\\Users\\Johan\\Desktop\\histo.txt"); // imports our file
        Scanner n = new Scanner(file); // creates scanner

        System.out.println("Reading values from: "+file);
        int oneToHund = 0;
        int other = 0;

        while (n.hasNextInt()){
            int i = n.nextInt();
            if (i >= 1 && i <= 100){
                oneToHund++;
            }
            else 
                other++;
        }

        System.out.println("Numbers between [1,100]: "+oneToHund);
        System.out.println("Numbers out of this range: "+other);

        System.out.println("1 - 10 | "+firstTen(n));


    }



   // method in question 

    private static int firstTen(Scanner n){
        int result = 0;
        while (n.hasNextInt()){
            int i = n.nextInt();
            if (i >= 1 && i <= 10){
                result++;
            }
        }return result;
    }

附加问题:我试着用main方法来做这件事,但似乎扫描器已经搜索了文件,第一个任务是检查数字1-100,它是这样工作的吗

firstTenn返回0,因为传递给已三叉游标的方法的扫描对象位于最后一个位置。添加n=新扫描文件;在调用firstTen方法之前

忘记查看!!!发现while循环中的值为false!你不是在文件中存储整数吗?那么,你就不再需要我们的帮助了?仍然想知道为什么这个值是假的。这一切都取决于文件histo.txt上的内容以及如何存储。