收集字符组成一个字符串并将其转换为整数

Collecting characters form a string and converting them to integers

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);
}

用户将输入由 space 分隔的 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。