2017-06-19 74 views
1

我试图解决这个问题:不正确的总和计算的

编写Java程序,读取来自用户的文件名。该文件预计包含最多20个整数。 声明一个大小为20的数组。读取文件中的所有值并将它们存储在数组中。请注意, 可以是文件中的任意数量的整数。最后,计算并显示数组中存储的所有整数的总和。 使用异常处理来检测:从那里一个非整数读

  • 使用无效数组索引的
  • 无效的文件名的文件,他的文件不存在

    • 不正确的输入
  • 我现在的问题是不正确的总和。这里是我的代码

    package labtask.pkg10; 
    import java.io.File; 
    import java.io.*; 
    import java.util.*; 
    import java.util.ArrayList; 
    
    public class task2 { 
        public static void main(String[] args) { 
         int integers[] = new int[20]; 
         Scanner read = new Scanner(System.in); 
         int sum = 0; 
         int num = 0; 
         String filename; 
         System.out.println("enter the file name "); 
         filename = read.next(); 
    
         try { 
          File file = new File(filename); 
          Scanner inputFile = null; 
          inputFile = new Scanner(file); 
    
          int i = 0; 
          while (inputFile.hasNext()) { 
           num = Integer.parseInt(inputFile.next()); 
    
           integers[i] = num; 
          } 
    
          for (int x = 0; x < 20; x++) { 
           sum += num; 
          } 
          System.out.println("sum are : " + sum); 
         } catch (FileNotFoundException e) { 
          System.out.println("file not found"); 
         } catch (NumberFormatException e) { 
          System.out.println("please enter only integer number"); 
         } 
        } 
    } 
    

    和我的文本文件:

    2 
    2 
    2 
    2 
    2 
    2 
    2 
    2 
    2 
    12 
    23 
    2 
    2 
    2 
    2 
    2 
    2 
    2 
    2 
    2 
    

    我得到以下输出:

    输入文件名
    gg.txt
    之和:40
    BUILD SUCCESSFUL(总时间:2秒)

    为什么总数没有正确计算?

    +0

    为什么你期望的总和是正确的?你的代码明确地忽略了数组并且总结了'num'。 – Tom

    +2

    提示:在这里只有一个**和**唯一的答案:当你的代码出乎意料地行为时,不要求助于其他人(至少不是第一步)。相反:使用** trace **语句使其*更清晰*您的代码正在做什么。换句话说:如果你不明白你的代码在做什么,那么就给你看。所以,跟踪东西,或学习使用调试器。 – GhostCat

    回答

    2

    正如埃伦已经回答了你的问题,我要来为其他人的解决方案,而不是具有使用int []的要求。异常处理需要添加,但是让我们假设该文件将确定例如着想 - 以下是你的完整的“求和逻辑”:

    Integer sum = Files.readAllLines(Paths.get("numbs.txt")) 
        .stream() 
        .mapToInt(Integer::parseInt) 
        .sum(); 
    System.out.println(sum); // 71 
    
    5

    您将最后一次输入添加20次而不是添加不同的数字。

    你的代码更改为:

    while(inputFile.hasNext()) 
    { 
        num = Integer.parseInt(inputFile.next()); 
    
        integers[i++] = num; 
    } 
    
    for (int x = 0 ; x<integers.length; x ++) 
    { 
        sum += integers[x]; 
    } 
    

    或者只是使用一个循环:

    while(inputFile.hasNext()) { 
        num = Integer.parseInt(inputFile.next()); 
        integers[i++] = num; 
        sum += num; 
    } 
    
    +0

    当我使用ur代码..我可以运行它,但它不会计算总和我为什么... – sozai

    +0

    哦其工作thx :) – sozai

    +0

    随着一个循环,整数数组甚至不再需要。如果使用更大的文件,它会限制产生ArrayIndexOutOfBoundException的风险。 –