0

Stuck on this mini question any help would be appreciated thanks a bunch

Write code that uses the input string stream inSS to read input data from string userInput, and updates variables userMonth, userDate, and userYear. Sample output if userinput is "Jan 12 1992": Month: Jan Date: 12 Year: 1992

 import java.util.Scanner;

 public class StringInputStream {
     public static void main (String [] args) {
         Scanner inSS = null;
         String userInput = "Jan 12 1992";
         inSS = new Scanner(userInput);`

         String userMonth = "";
         int userDate = 0;
         int userYear = 0;

         /* Your solution goes here  */

         System.out.println("Month: " + userMonth);
         System.out.println("Date: " + userDate);
         System.out.println("Year: " + userYear);

         return;
    }
}
FacelessTiger
  • 89
  • 1
  • 1
  • 11
panzer67
  • 3
  • 1
  • 1
  • 1

2 Answers2

0

Since we already know that userInput is a string, we can tokenize it into space separated strings, using split() function on strings and store it in an array of strings.

String[] dateArray = userInput.split(" ");

This will give you 3 separate strings. "Jan","12" , "1992". Parse the latter 2 as integers.

userMonth = dateArray[0];

try{ userDate = Integer.parseInt(dateArray[1]); userYear = Integer.parseInt(dateArray[2]); } catch(Exception e) { e.printStackTrace(); }

Hope that helps.

jkasper
  • 236
  • 4
  • 19
0

Using Scanner you can set userMonth straight to the month

String userMonth = inSS.next();

It will recognize the white space (space) and just get the month, then it will cut that out of the String that the Stream has. Now we can set the userDate and userYear using nextInt

int userDate = inSS.nextInt();
int userYear = inSS.nextInt();

This works because the first nextInt() will delete the 12 leaving just the 1992 which the second int takes.

This will produce the output:

Month: Jan
Date: 12
Year: 1992
FacelessTiger
  • 89
  • 1
  • 1
  • 11