额外+标志我的计划

时间:2016-04-04 14:59:54

标签: java

我为我的计算机科学课编写了一个程序,它读取文件并导入数据,然后只添加数字,但似乎是添加了一个额外的符号。

import java.io.*; //necessary for File and IOException 
import java.util.*; //necessary for Scanner
public class Tester
{
public static void main( String args[] ) throws IOException
   {
    Scanner sf = new Scanner(new File("/Volumes/DVLUP Flash/Numbers.txt"));

    int maxIndx = -1; //-1 so when we increment below, the first index is 0
    String text[] = new String[1000]; //To be safe, declare more than we
        while(sf.hasNext( ))
        {
            maxIndx++;
            text[maxIndx] = sf.nextLine( ); 
            //System.out.println(text[maxIndx]); //Remove rem for testing
        }
        sf.close();

        for(int j =0; j <= maxIndx; j++)
        {
            Scanner sc = new Scanner(text[j]);
        }
        String answer = ""; //We will accumulate the answer string here. 
        int sum; //accumulates sum of integers
        for(int j = 0; j <= maxIndx; j++)
        {
            Scanner sc = new Scanner(text[j]);
            sum = 0;
            answer = ""; 
            while(sc.hasNext())
            {
                int i = sc.nextInt();
                answer = answer + i + " + ";
                sum = sum + i; 
            }
            //sc.next();
            answer = answer + " = " + sum; 
            System.out.println(answer);
        } 
    }
}

输出

12 + 10 + 3 + 5 +  = 30
18 + 1 + 5 + 92 + 6 + 8 +  = 130
2 + 9 + 3 + 22 + 4 + 11 + 7 +  = 58

在最后一个号码之后还有一个额外的号码,我该如何解决?

3 个答案:

答案 0 :(得分:2)

在最后一次迭代之后,你有一个“额外”加号,因为这是你打印它的方式。您正在使用os.rename(FileName, '{0}_{1}_{2}.png'.format( FileName.replace(".png", ""), time_stamp.replace(":", "-"), name_string.replace(" ", "_") )) 结束String,因为您可以在while循环中看到它。

要更改它,请在值之前添加+

+

或者,如果您使用Java 8,则可以使用if(sc.hasNext()) { int i = sc.nextInt(); answer = i + ""; sum += i; while(sc.hasNext()) { i = sc.nextInt(); answer = answer + " + " + i; sum = sum + i; } } 作为

StringJoiner

答案 1 :(得分:1)

        while(sc.hasNext())
        {
            int i = sc.nextInt();
            answer = answer + i + " + ";
            sum = sum + i; 
        }

answer = answer.substring(0, answer.length()-1);

答案 2 :(得分:0)

一种选择是在附加其他之前的每个数字之前有条件地添加一个加号,而不是第一个数字:

answer = ""; 
while(sc.hasNext()) {
    int i = sc.nextInt();
    if (answer.length() > 0) {
        answer += " + ";
    }
    answer = answer + i;
    sum = sum + i; 
}