当前位置: 动力学知识库 > 问答 > 编程问答 >

java - How do I manage console user input made up of a char and an int?

问题描述:

I created a 2D array game that looks like this:

.........H

...X......

[email protected]@@..

...X......

[email protected]

.XXXXX.X..

.......X..

[email protected]

.......X..

P.........

Next option ?

The player’s lives increment by one upon ‘eating’ a doughnut, which makes it optional to jump grids. So instead of pressing either ‘U’, ’D’, ’L’ or ’R’ and hitting enter to move from one grid to the next, the player, upon eating one doughnut has the option to enter ‘U2’ to jump one grid and land on the higher grid or say ‘R2’ to jump one grid to the right etc. And if the player eats yet a second doughnut, (s)he can now enter commands like ‘U3’ or 'D3' to jump two grids and so on.

I have coded the following, without much success:

// Declare a variable to hold values for use in regular movements

private static char opt1;

// Declare a variable to hold values for use in specifying square numbers for super moves

private static int opt2;

public static void main(String[] args) {

String opt;

// The code below is a part of a do-while loop that keeps the game running till it ends naturally

System.out.print("Next option ?");

opt = scan.next();

if (lives == 1) {

opt1 = opt.charAt(0);

} else if (lives > 1) {

opt1 = opt.charAt(0);

opt2 = Character.getNumericValue(opt.charAt(1));

}

With only 1 life, it works perfectly but when the lives increment the issue I am having is as thus:

The console now expects two inputs, that is, a char and an int which I understand is because the program switches to the ‘else’ part of the code above but I want a scenario where even with lives more than one, if the user inputs a char like ‘U’, ’D’, ’L’, ’R’, ‘Z’ (undo move) or ’M’ (mark player movement trail), the program will just read it and perform the function without expecting an int. Because as of now, when the lives are above one and I enter a single char and push enter, it hits me with the following:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1

at java.lang.String.charAt(String.java:658)

Thanking you in advance for your advice and directions.

Please let me know if you need any further clarification.

分享给朋友:
您可能感兴趣的文章:
随机阅读: