简体   繁体   English

如何摆脱那个讨厌的领先加号?

[英]How to get rid of that pesky leading plus sign?

I have a code that basically reads from a text file. 我有一个基本上从文本文件中读取的代码。 There is a leading plus sign when it outputs because the answer is printed in a loop. 输出时有一个前导加号,因为答案是循环打印的。 How do I get rid of that singular leading plus sign? 如何摆脱那个奇异的领先加号? All I can think to do is to convert the ENTIRE THING to a string and then take out the first three indexes but that's way too complicated. 我所能想到的只是将整个过程转换为字符串,然后取出前三个索引,但这太复杂了。 Is there a simple way to just rearrange the logic and do it? 有没有一种简单的方法来重新排列逻辑并做到这一点?

My code: 我的代码:

    /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package importtextfiles;

/**
 *
 * @author Hana
 */
import java.io.*;
import java.util.*;
public class InputNumData {
    public static void main(String args[]) throws IOException
    {
        Scanner sf = new Scanner(new File("C:\\Users\\Hana\\SkyDrive\\CompSci\\Programming\\importTextFiles\\meow.txt"));
        int maxIndx = -1; //so the first index is 0

        String text[] = new String[1000];

        while(sf.hasNext()){
            maxIndx++;
            text[maxIndx] = sf.nextLine();
            System.out.println(text[maxIndx]);
        }

        sf.close();

        String answer = "";
        int sum;

        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;
            }
            answer = answer + " = " + sum;
            System.out.println(answer);
        }
    }
}

My output: 我的输出:

run:
12 10 3 5
18 1 5 92 6 8
2 9 3 22 4 11 7
 + 12 + 10 + 3 + 5 = 30
 + 18 + 1 + 5 + 92 + 6 + 8 = 130
 + 2 + 9 + 3 + 22 + 4 + 11 + 7 = 58
BUILD SUCCESSFUL (total time: 0 seconds)

meow.txt: meow.txt:

12 10 3 5
18 1 5 92 6 8
2 9 3 22 4 11 7

Just change this line to 只需将此行更改为

answer = answer.isBlank() ? i : answer + " + " + i;

For more details on how it works refer this . 有关它的工作原理是指更多的细节

Take your while loop, and fix the first value: 拿你的while循环,并修复第一个值:

//Set up first value
int i = sc.nextInt();  //might want to check for hasNext() here 
answer = i;
sum = sum + i;

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

First thing is not to use concatenation in a loop. 首先,不要在循环中使用连接。 Something like: 就像是:

String result = ""
for (...) {
    result = result + "some additonal data";
}

Creates several intermediate string objects and that's bad practice. 创建几个中间字符串对象,这是不好的做法。 It should be replaced with: 它应该替换为:

StringBuilder sb = new StringBuilder();
for (...) {
    sb.append( "some additional data" );
}
result = sb.toString();

Which allows you to add strings without creating a new string object until you have finished appending. 这使您可以在完成追加之前添加字符串而无需创建新的字符串对象。

Now that we are using a StringBuilder , you can have several solutions to the initial plus problem. 现在我们正在使用StringBuilder ,您可以使用多个解决方案来解决初始加问题。 The first, which would also work with the non-recommended string concatenation, is to keep a flag that tells you if this is the "first operand". 第一个,也适用于非推荐的字符串连接,是保留一个标志,告诉你这是否是“第一个操作数”。 Change your while loop to: while循环更改为:

StringBuilder sb = new StringBuilder();
boolean firstOperand = true;

while(sc.hasNext()){
    int i = sc.nextInt();
    if ( firstOperand ) {
        firstOperand = false;
    } else {
        sb.append( " + " );
    }
    sb.append( i );
    sum = sum + i;
}
answer = sb.toString();

Another way, which is possible with a StringBuilder is to remove the extra " + " after you finish the loop. 使用StringBuilder可能的另一种方法是在完成循环后删除额外的" + " In this case, it's better to add the " + " after each operand, so that the extra one will be at the end. 在这种情况下,最好每个操作数之后添加" + " ,以便额外的一个在最后。 It's more efficient to delete from the end of a StringBuilder than from its beginning: StringBuilder的末尾删除比从开头删除更有效:

StringBuilder sb = new StringBuilder();

while(sc.hasNext()){
    int i = sc.nextInt();
    sb.append( i ).append( " + " );
    sum = sum + i;
}
if ( sb.length() > 0 ) {
    sb.setLength( sb.length() - 3 );
}
answer = sb.toString();

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

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