gpt4 book ai didi

java - 如何在没有空格的情况下进行扫描仪输入

转载 作者:行者123 更新时间:2023-11-30 02:36:24 25 4
gpt4 key购买 nike

我有一个作业问题需要我写一个

Program that takes three names and their scores from a user by using delimiters. Example:

Tom:54, Matt:12, Ali:89

当 Java 分配 user2Score 时,我不断收到输入不匹配异常。我目前正在测试我的程序,但扫描仪似乎将 user2 视为 "Matt" 而不是 "Matt"。我不确定我的分隔符语法是否正确。如有任何反馈,我们将不胜感激!

import java.util.Scanner;

public class General {

public static void main(String[] args) {

Scanner input = new Scanner(System.in).useDelimiter("[: | ,*\\s]");

String user1;
String user2;
String user3;

int user1Score;
int user2Score;
int user3Score;

System.out.println("Please enter the user name and their score:");
user1 = input.next();
user1Score = input.nextInt();
user2 = input.next();
user2Score = input.nextInt();
user3 = input.next();
user3Score = input.nextInt();


System.out.println(user1 + " " + user1Score + "\n" + user2 + " " + user2Score);
}

}

最佳答案

您可以使用字符串的trim()方法。这会消除字符串开头和结尾的所有空格。

关于java - 如何在没有空格的情况下进行扫描仪输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42931266/

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