【发布时间】:2014-11-03 04:03:05
【问题描述】:
对于这个程序,我将输入作为具有以下格式的字符串:名称,后跟以空格分隔的整数。系列中可以有一个或多个整数。它的输出最终是系列的名称及其总和。这是输出应该是什么的示例:
Series? seriesname 1 3 5 7 11
sum(seriesname) = 27
我的代码有问题,这行一直有问题(例外):
int number = Integer.parseInt(series.substring(start, space));
我已经搬了很多地方,但这就是我现在所拥有的:
import java.util.Scanner;
public class NamePlusAddingInts {
public static String series;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Series? ");
series = scan.nextLine();
String name = series.substring(0, series.indexOf(' '));
System.out.print("Sum(" + name + ") = " + number);
}
public static int adding() {
int space = series.indexOf(' ');
while (space != -1) {
int start = space + 1;
int number = Integer.parseInt(series.substring(start, space));
number = number + number;
space++;
}
return number;
}
}
【问题讨论】:
-
I am having problems with my code, It keeps having issues with the:- 有什么问题? -
为什么您的代码不起作用?什么是错误/异常?
-
substring的参数是开始字符和结束字符(加 1)。您已经设置好开始总是在结束字符之后。那是行不通的。 -
我认为你想要的
substring是让程序将子字符串放到 next 空间。这似乎是正确的,但为了做到这一点,您必须告诉程序找到下一个空格。您可能想要使用不同版本的indexOf。这记录在this link。