[英]How to take scanner input without space
I have a homework question that wants me to write a 我有一个作业问题,希望我写一个
Program that takes three names and their scores from a user by using delimiters.
该程序使用定界符从用户那里获取三个名称及其分数。 Example:
例:
Tom:54, Matt:12, Ali:89
I keep getting an input mismatch exception when Java is assigning user2Score
. 当Java分配
user2Score
时,我不断收到输入不匹配异常。 I am currently testing my program but scanner seems to take in user2
as " Matt"
instead of "Matt"
. 我目前正在测试我的程序,但扫描仪似乎将
user2
视为" Matt"
而不是"Matt"
。 I'm not sure if my delimiter syntax is correct. 我不确定我的定界符语法是否正确。 Any feedback would be greatly appreciated!
任何反馈将不胜感激!
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);
}
}
you can use the trim()-method of String. 您可以使用String的trim()方法。 This elimates all spaces at the beginning and at the end of the string.
这消除了字符串开头和结尾的所有空格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.