【发布时间】:2015-02-08 20:31:55
【问题描述】:
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int rounds, antonia = 100, david = 100;
int rolla, rolld;
String score;
String[] scorenospace;
System.out.println("How many rounds would you like to play? (1-15)");
rounds = scan.nextInt();
while (rounds > 0) {
score = scan.nextLine();
scorenospace = score.split(" ");
rolla = Integer.parseInt((scorenospace[0]));
rolld = Integer.parseInt((scorenospace[1]));
if (rolla > rolld) {
david = david - rolla;
} else if (rolla < rolld) {
antonia = antonia - rolld;
} else if (rolla == rolld) {
}
rounds--;
}
System.out.println(antonia + david);
}
用户将输入两个用空格分隔的数字。我想单独收集和比较作为字符串输入的 2 个数字。我该怎么做呢?
我的代码抛出了越界异常。我很困惑。
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int rounds, antonia = 100, david = 100;
int rolla, rolld=0;
String score;
System.out.println("How many rounds would you like to play? (1-15)");
rounds = scan.nextInt();
while (rounds > 0) {
score = scan.nextLine();
rolla = score.charAt(0);
rolld = score.charAt(2);
if (rolla > rolld) {
david = david - rolla;
} else if (rolla < rolld) {
antonia = antonia - rolld;
} else if (rolla == rolld) {
}
rounds--;
}
System.out.println(antonia + david);
}
我也尝试了 chatAt 方法,但似乎无法让代码工作。任何帮助将不胜感激。我为平庸的代码质量道歉。我是编程新手,我正在努力自己学习。非常感谢大家的帮助, 干杯:)
【问题讨论】:
-
通过什么输入会引发 IOOB?法律意见?
-
您提供的输入是什么?
-
使用 char 你实际上会得到 char,所以你需要做类似
rolla = (int)score.charAt(1) - 48; -
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0 at java.lang.String.charAt(String.java:646) at doubledicesimple.main(doubledicesimple.java:15)这是它抛出的错误,程序运行不够远让我输入任何分数,它在我输入多少轮后立即抛出异常玩 -
它不会向我抛出任何错误吗?您尝试的输入是什么?按什么顺序输入?
标签: java arrays string int compare