我有一个基本上从文本文件中读取的代码.输出时有一个前导加号,因为答案是循环打印的.如何摆脱那个奇异的领先加号?我所能想到的就是将整个过程转换为字符串,然后取出前三个索引,但这太复杂了.有没有一种简单的方法来重新排列逻辑并做到这一点?
我的代码:
/* * 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)
meow.txt:
12 10 3 5 18 1 5 92 6 8 2 9 3 22 4 11 7
StackFlowed.. 5
只需将此行更改为
answer = answer.isBlank() ? i : answer + " + " + i;
有关它的工作原理是指更多的细节此.
只需将此行更改为
answer = answer.isBlank() ? i : answer + " + " + i;
有关它的工作原理是指更多的细节此.