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个数字。我想单独收集并比较输入为字符串的2个数字。我该怎么做呢?
我的代码抛出了一个outofbounds异常。我很困惑。
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方法,但似乎无法让代码工作。任何帮助将不胜感激。我为代码的平庸质量道歉。我是编程新手,我正在尽我所能地学习。非常感谢所有的帮助, 干杯:)
答案 0 :(得分:0)
如果您希望输入有点像这样,那就猜测一下:
3 12 17 // where 3 is rounds and 12 and 17 are values
23 45 // 23 and 45 again as values
12 36 // 12 and 36 again as values
然后您可以将代码更改为:
rounds = Integer.parseInt(scan.nextLine());
while (rounds > 0) {
score = scan.nextLine();
rolla = Integer.parseInt(score.split(" ")[0]);
rolld = Integer.parseInt(score.split(" ")[1]);
.
.
.
}
添加另一件事: score.charAt(0)会为你提供ascii等价物。