简体   繁体   English

Java:从文本文件中获取整数后,扫描仪显示零

[英]Java: Scanner shows zeroes after taking integers from text file

I am using Scanner class to fetch Integers from my Integers.txt file. 我正在使用Scanner类从我的Integers.txt文件中获取整数。 The bug is that I am not getting the exact Integers in Array. 错误是我没有在Array中获得确切的整数。 I get zeros only. 我只有零。 Although, the summation is correct when I try to find Minimum value, I get 0 as Minimum value. 虽然,当我尝试找到最小值时,总和是正确的,但我得到0作为最小值。 What am I doing wrong? 我究竟做错了什么?

This is the code: 这是代码:

/**
* Program to take various integers from users as input and stores them 
in file called "Integers.txt"
* (a) The process should continue until user enters -9999 as input
* (b) Calculate summation of all the numbers available in Integers.txt
* (c) Find Maximum & Minimum Numbers from File
* (d) Sort the numbers available in the Integers.txt into 
    "SortedIntegers.txt"
* (e) Sort the Integers.txt file  
**/

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

class Exercise8{
    public static void main(String args[]){
        Scanner scan = new Scanner(System.in);
        // Code snippet to create a file named Integers.txt
        try{
            File integerFile = new File("Integers.txt");
            integerFile.createNewFile();    
        }catch(Exception e){
    }


    int choice = 0;
    do{
        System.out.println("\nSelect an Operation: ");
        System.out.println("(1) Input Integers in Integers.txt");
        System.out.println("(2) Calculate sum of all the numbers available in Integers.txt");
        System.out.println("(3) Find Maximum & Minimum of Numbers from File");
        System.out.println("(4) Sort the Integers.txt");
        System.out.println("(5) Sort the Numbers into SortedIntegers.txt");     
        try{
        System.out.print("\nEnter Choice: ");
        choice = scan.nextInt();
        switch(choice){
                case 1: 
                    try{
                        FileWriter fstreamIntegers = new FileWriter("Integers.txt");
                        BufferedWriter outIntegers = new BufferedWriter(fstreamIntegers);       
                        //Scanner scan = new Scanner(System.in);
                        System.out.print("How many numbers do you want to enter?: ");
                        int num = scan.nextInt();
                        String integers[] = new String[num+1];

                        for(int i = 0; i < integers.length; i++){
                            integers[i] = scan.nextLine();
                            outIntegers.write(integers[i]+"\n");
                        }
                        outIntegers.close();
                    }catch(IOException e){
                        e.printStackTrace();
                    }
                    break;

                case 2:                     
                    try{
                        File integerFile = new File("Integers.txt");                        
                        Scanner inFile = new Scanner(integerFile);
                        //int size = inFile.nextInt();
                        int[] arrIntegers = new int[(int)integerFile.length()];
                        int i = 0;
                        while(inFile.hasNextInt()){
                            arrIntegers[i++] = inFile.nextInt();
                            /*inFile.next();
                            if(inFile.hasNextInt()){

                            }*/
                        }
                        int sum = 0;
                        for(int j = 0; j < arrIntegers.length; j++){
                            System.out.println(arrIntegers[j]);
                            sum += arrIntegers[j];
                        }
                        System.out.println("\nSum of the integers present in Integers.txt is " + sum);

                    }catch(Exception e){
                    }                       
                    break;

                    case 3:                     
                    try{
                        File integerFile = new File("Integers.txt");                        
                        Scanner inFile = new Scanner(integerFile);
                        int[] arrIntegers = new int[(int)integerFile.length()];
                        int i = 0;
                        while(inFile.hasNextInt()){
                            arrIntegers[i++] = inFile.nextInt();
                            /*if(!inFile.hasNextInt()){
                                inFile.next();
                            }*/
                        }

                        int max = arrIntegers[0];               
                        for(int j = 0; j < arrIntegers.length; j++){
                            if(max < arrIntegers[j]){
                                max = arrIntegers[j];
                            }
                        }
                        System.out.println("\nMaximum number out of numbers present in Integers.txt is " + max);

                        int min = arrIntegers[0];               
                        for(int j = 0; j < arrIntegers.length; j++){
                            if(min > arrIntegers[j]){
                                min = arrIntegers[j];
                            }
                        }
                        System.out.println("\nMinimum number out of numbers present in Integers.txt is " + min);

                    }catch(Exception e){
                    }                       
                    break;

                default: 
                    if(choice == -9999){
                    }else{
                        System.out.println("\n*****Enter Valid Choice!*****");
                    }
        }
        }catch(InputMismatchException e){
            System.out.print("\n*****Enter Valid Choice!*****");
            scan.next();                
        }               
    }while(choice != -9999);
    scan.close();
  }
}

This is the Integers.txt file 这是Integers.txt文件

1
2
3
4
5

The output: 输出:

Output Image 输出图像

int[] arrIntegers = new int[(int)integerFile.length()]; creates an array of size the number of bytes of the file integerFile . 创建一个数组,该数组的大小为文件integerFile的字节数。

Then the while loop executes i++ at each iteration so that when the following for loop iterating over j executes System.out.println(arrIntegers[i]); 然后while循环在每次迭代时执行i++ ,以便在j进行以下for循环迭代时,执行System.out.println(arrIntegers[i]); (note i , and not j ), i points to an index that has never been set in the array, therefore returning 0 , the default int value. (请注意i ,而不是j ), i指向数组中从未设置过的索引,因此返回默认值int 0

That is why 0 is printed at each iteration while the sum is correct! 这就是为什么每次迭代都将0打印而总和正确的原因!

You might have created Integers.txt in wrong path.. First try running with option 1 first and enter the 5 values 1, 2, 3, 4, 5 so that file is created from the program at the same path where you are trying to read... Next try running option 2, you will see the sum getting correctly displayed.. 您可能在错误的路径中创建了Integers.txt。首先尝试首先使用选项1运行,然后输入5个值1、2、3、4、5,以便从程序在尝试创建路径的同一路径中创建文件。阅读...接下来尝试运行选项2,您将看到正确显示总和。

Try printing the file path using below code and check what values this file has. 尝试使用以下代码打印文件路径,并检查此文件具有哪些值。

System.out.println("File path :"+ integerFile.getAbsolutePath()); System.out.println(“ File path:” + integerFile.getAbsolutePath());

You have referred i in place of j in your for loop for case '2' . 您已经在case '2' for循环中用i代替了j So change your for loop to as follows for case '2' : 因此,将case '2' for循环更改为以下内容:

for(int j = 0; j < arrIntegers.length; j++){
    System.out.println(arrIntegers[j]);
    sum += arrIntegers[j];
}

I was supposed to be using ArrayList for dynamic array. 我应该将ArrayList用于动态数组。 I am posting the code snippet of case 2 here which worked for me. 我在这里发布了案例2的代码段,该代码段对我有用。

case 2:                     
                    try{
                        File integerFile = new File("Integers.txt");                        
                        Scanner inFile = new Scanner(integerFile);
                        //int size = inFile.nextInt();
                        List<Integer> listIntegers = new ArrayList<>();
                        /*for(int i = 0; i < upperBound; i++) {
                            sum.add(i);
                        }
                        // necessary to convert back to Integer[]
                        Integer[] sumArray = sum.toArray(new Integer[0]);*/
                        //int[] arrIntegers = new int[(int)integerFile.length()];
                        int i = 0;
                        while(inFile.hasNextInt()){
                            //arrIntegers[i++] = inFile.nextInt();
                            i = inFile.nextInt();
                            listIntegers.add(i);
                            i++;
                            /*inFile.next();
                            if(inFile.hasNextInt()){

                            }*/
                        }
                        Integer[] arrIntegers = listIntegers.toArray(new Integer[0]);
                        int sum = 0;
                        for(int j = 0; j < arrIntegers.length; j++){
                            System.out.println(arrIntegers[j]);
                            sum += arrIntegers[j];
                        }
                        System.out.println("\nSum of the integers present in Integers.txt is " + sum);

                    }catch(Exception e){
                    }                       
                    break;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM