Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/373.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 - Fatal编程技术网

Java 抛出异常并打印输出的扫描仪

Java 抛出异常并打印输出的扫描仪,java,Java,所以需要一个方法来读取包含4个整数(1,2,3,4)的txt文件并抛出异常。我想我的扫描仪是正确的。。。但是我想打印扫描仪在我的主方法中读取的值。我不知道如何使用System.out.println()实现这一点。扫描仪不在主方法中。 这是我的密码: public static void scan() { String fileInputName = "data.txt"; Scanner sc = null; try { sc = ne

所以需要一个方法来读取包含4个整数(1,2,3,4)的txt文件并抛出异常。我想我的扫描仪是正确的。。。但是我想打印扫描仪在我的主方法中读取的值。我不知道如何使用System.out.println()实现这一点。扫描仪不在主方法中。 这是我的密码:

public static void scan()
{     
    String fileInputName  = "data.txt";
    Scanner sc = null;  

    try {
        sc = new Scanner(new BufferedReader(new FileReader(fileInputName)));
        while (sc.hasNextLine()) 
        {                     
            sc.nextInt();
        }
    }
    catch (FileNotFoundException e) 
        {
            e.printStackTrace();
        }
    finally
    {
        if (sc != null)
            sc.close();  
    }           
}

您必须将扫描分配给一个变量,然后打印它:

更改方法的接口

public List<Integer> void scan()
然后在main中,反复浏览列表并将其打印出来:

list = scan();

for (Integer i : list){
    System.out.println(i);
}

您可以将int go指定为变量,然后按如下方式打印变量:

System.out.println(variableInt);
或者,您可以在访问它时打印它,如下所示:

System.out.println(sc.nextInt());
另外,要知道println在打印完东西后会移动一个新行。如果要避免这种情况,只需将其更改为:

System.out.print(whatever);

System.out.println(sc.nextInt());您的可能副本可能还希望提到他/她应该在while循环中这样做。这不起作用,因为我的扫描仪不在我的主方法中。while循环在扫描仪中进行。我的目标是在方法中不包含任何system.out.println()。只有主方法。在main方法中,我想调用并撬出txt文件中的整数
System.out.println(sc.nextInt());
System.out.print(whatever);