gpt4 book ai didi

java - 从字符串中收集字符并将其转换为整数

转载 作者:太空宇宙 更新时间:2023-11-04 14:10:24 25 4
gpt4 key购买 nike

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 个数字。我该如何去做呢?

我的代码抛出越界异常。我很困惑。

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 方法,但似乎无法让代码工作。任何帮助将不胜感激。我对代码质量平庸表示歉意。我是编程新手,正在尝试自己学习尽可能多的知识。非常感谢大家的帮助,干杯:)

最佳答案

只是猜测您是否希望输入像这样:

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 码。

关于java - 从字符串中收集字符并将其转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28399027/

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