0

In my program I want to take an input from the user in the format of "String Int Int". For example, "F 5 200".

I then want to store these values into three different variables. How would I go about doing this?

import java.util.Scanner;

public class Test {

 public static void main(String args[])
   {
      String s;

      Scanner in = new Scanner(System.in);

      System.out.println("Enter a command");
      s = in.nextLine();

      String str = s; 
        String[] arrOfStr = str.split(" ", 3); 

        for (String a : arrOfStr) 
            System.out.println(a); 



   }

}

I've got to the point of splitting the string and outputting the result. However I'm not sure how to store the outputs into variables with the correct data type.

2 Answers 2

1

They are all String variables so you realy have to know the order of the data so you can parse the string into int type

   String[] arrOfStr = str.split(" ", 3);
 String str1 =  arrOfStr[0];
 int int2 = Integer.parseInt (arrOfStr[1]);
 int int3 =  Integer.parseInt (arrOfStr [2]);
Sign up to request clarification or add additional context in comments.

2 Comments

You can't assign a String to a char variable, as your code does with str1. So I had to downvote that. Please correct that, and I'll happily upvote.
Yes my bad i missed that
1

The three values are available in the array arrOfStr. So you could have three variables and assign each of them to arrOfStr[0], arrOfStr[1] and arrOfStr[2].

so the code snippet could look like the below in this case

String[] arrOfStr = str.split(" ", 3); 
String c = arrOfStr[0];
int val1 = Integer.parseInt(arrOfStr[1]);
int val2 = Integer.parseInt(arrOfStr[2]);

2 Comments

You can't assign a String to an int variable, as your code does with val1 and val2. So I had to downvote that. Please correct that, and I'll happily upvote.
Still using char instead of String for c (what I missed when reading first).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.