收集字符形成字符串并将其转换为整数


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 等效项。

相关内容

  • 没有找到相关文章

最新更新