Java splitting input

I am trying to write simple code for my project if the user type

walk 10

I need to use the โ€œwalkโ€ command in my walk (distance) method, since distance = 10 I have something like this

while (!quit) {
Scanner in = new Scanner(System.in);
String input = in.nextLine();
// if (walk x is typed) {
walk(x);
}
}

I use java.util.scanner and another problem is that my walk (int x) method uses int so I need to convert the String input to int

I searched the Internet for a while, but could not find what I was looking for (or I did not understand it)

So in any case, I would appreciate it if you could help me.

, โ€‹โ€‹ "", , null int ( )

                    try {
                    Integer.parseInt(splitStrings[1]);
                    }
                    catch(NumberFormatException e) {
                    System.out.println("error: " + e);
                    }

- ( try/catch) , ,

,

            if ("walk".equals(splitStrings[0])) {
                if (splitStrings.length == 2) {
                int distance = Integer.parseInt(splitStrings[1]);
                Robot.walk(distance);
                }
                if (splitStrings.length != 2) {
                    System.out.println("Entry must be like walk 10");
                }
            }
+3
6

split() . .

String s = 'walk 10';
String[] splitStrings = s.split(" ")

, 10, :

String distanceToWalk = splitStrings[1]

int, parseInt() Integer

Integer.parseInt(distanceToWalk);

.

+5

, ( 1) , .

Integer x = Integer.parseInt(input.split(" ")[1])
+7

You can use the method Integer.parseInt():

int distance = Integer.parseInt(input);
+1
source

Try:

String s = 1;
int i = Integer.parseInt(s); // returns 1
0
source

Assuming you cross out the integer part from the string, e.g. leaving input

"walk 10" with "10", just use something like

// say you've parsed the "number" portion into a variable "inputString"
int x;
x= Integer.parseInt(inputString);
0
source

You can use this:

// For read the input
InputStreamReader streamReader = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(streamReader);
String input = reader.readLine();

If you prefer to use Scanner, then

Scanner sc = new Scanner(System.in);
String input = sc.nextLine();

Then:

StringTokenizer st = new StringTokenizer(input);
if (st.countTokens == 2) { // Only for two tokens "walk 100", "return 10"
    String method = st.nextToken();
    if (method.equals("walk") { // if you have more methods like "walk"
        int distance = Integer.parseInt(st.nextToken());
        walk(distance); // walk
    }
}

If you want to read more lines

for(String input; sc.hasNextLine();) {
    input = sc.nextLine();

    // do something

}

or

for(String input; (input = reader.readLine()) != null;) {

    // do something

}
0
source

All Articles