gpt4 book ai didi

java - 我程序上的额外 + 标志

转载 作者:行者123 更新时间:2023-11-29 04:48:06 31 4
gpt4 key购买 nike

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

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

最后一个数字后面多了一个,我该如何解决?

最佳答案

在最后一次迭代后,您将获得一个“额外”加号,因为这是您打印它的方式。您将以 + 结束 String,因为它可以在您的 while 循环中看到。

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

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

或者,如果您使用 Java 8,则可以将 StringJoiner 用作

StringJoiner joiner = new StringJoiner(" + ");
while(sc.hasNext())
{
i = sc.nextInt();
// This automaticly includes a " + " between the values.
joiner.add(String.valueOf(i));
sum = sum + i;
}

关于java - 我程序上的额外 + 标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36406181/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com