我有一个基本上从文本文件中读取的代码。输出的时候前面有个加号,因为答案是循环打印的。我如何摆脱那个单一的前导加号?我所能想到的就是将整个事物转换为字符串,然后取出前三个索引,但这太复杂了。是否有一种简单的方法来重新排列逻辑并执行此操作?

我的代码:

    /* 
 * 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); 
        } 
    } 
} 

我的输出:

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) 

喵.txt:

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

请您参考如下方法:

只需将此行更改为

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

有关其工作原理的更多详细信息,请参阅 this .


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!