简体   繁体   English

将扫描仪与字符串拆分器一起使用

[英]Using a Scanner with a String Splitter

I am trying to use a string splitter to display user input eg 1,2 coordinates to display on a console. 我正在尝试使用字符串拆分器来显示用户输入,例如要在控制台上显示的1,2坐标。 I don't get any errors when I run my code. 运行代码时没有任何错误。 However, my attempt to use the splitter does not seem to work. 但是,我尝试使用分离器似乎无效。

Scanner scanner = new Scanner(System.in);
System.out.println("Enter a row and column number at which to shoot (e.g., 2,3): ");
String[] coordinates = scanner.nextLine().split(",");
if (coordinates.length != 2) {
    System.out.println("Please enter coordinates in the correct format.");
    System.out.println("\nPlayer 1 Please take your turn:");
    continue;
}

System.out.println("\nEnter Mine location:");

System.out.println("\nPlease Enter x position for your Mine:");
System.in.read(byt);
str = new String(byt);
row = Integer.parseInt(str.trim()); 

System.out.println("\nPlease Enter y position for your Mine:");
System.in.read(byt);
str = new String(byt);
col = Integer.parseInt(str.trim());

Your use of System.in.read(...) is dangerous code and is not doing what you think it's doing: 您对System.in.read(...)是危险的代码,并且没有执行您认为正在做的事情:

System.in.read(byt); // *****
str = new String(byt);
row = Integer.parseInt(str.trim()); 

Instead use a Scanner, something that you already have , and either call getNextInt() on the Scanner, or get the line and parse it. 取而代之的是使用Scanner( 已经拥有的东西 getNextInt() ,然后在Scanner上调用getNextInt()或获取该行并对其进行解析。

Also, you never use the Strings held in the coordinates array -- why get the Strings if you are ignoring them? 另外,您永远不要使用坐标数组中保存的字符串-如果忽略它们,为什么要获取字符串?


You ask about: 您询问:

Scanner scanner = new Scanner(System.in); 
System.out.println("Enter a row and column number at which to shoot (e.g., 2,3): "); 
str = scanner.nextInt().split(","); 

but then see that the compiler won't allow this since you're trying to call a method on the int primitive that scanner.nextInt() returns. 但是然后看到编译器不允许这样做,因为您试图在scanner.nextInt()返回的int原语上调用方法。

My recommendation to use Scanner#nextInt() was as a replacement for you misuse of System.in.read(...) . 我建议使用Scanner#nextInt()来代替您对System.in.read(...)滥用。 If instead you want the user to enter two numbers on one line, separated by a comma, then you're best bet is to use String.split(",") , although, I think it might be better to use String.split("\\\\s*,\\\\s*") to get rid of any white space such as spaces hanging about. 相反,如果您希望用户在一行上输入两个数字,并用逗号隔开,那么最好是使用String.split(",") ,不过,我认为使用String.split("\\\\s*,\\\\s*")可能更好String.split("\\\\s*,\\\\s*")摆脱任何空白,例如周围闲逛。 This way the split should work for 1,1 as well as 1, 2 and 1 , 2 , and then you can parse the items held in the array via Integer.parseInt(...) . 这样,拆分应该适用于1,1以及1, 21 , 2然后您可以通过Integer.parseInt(...)解析数组中保存的项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM