1

I need to write a program that makes a user to type string date (ex. 10/21) once, and convert that string into integers. I suppose splitting is necessary before parsing?

import java.util.Scanner;
public class ConvertDates {
   public static void main(String[] args) {
      Scanner input = new Scanner(System.in);
      System.out.print("Please input a date (mm/dd): ");
      String k = input.next();
      k = String.split("/");
      int mm = Integer.parseInt(k);
      int dd = Integer.parseInt(k);

4 Answers 4

6

When you split a string, you don't get a string, you get an array of strings. So you would need to call

String[] k2 = k.split("/"); 

then you can get your month and day with

int mm = Integer.parseInt(k2[0]);
int dd = Integer.parseInt(k2[1]);
Sign up to request clarification or add additional context in comments.

Comments

4
String[] tokens = k.split("/");
int mm = Integer.parseInt(tokens[0]);
int dd = Integer.parseInt(tokens[1]);

Since split() method returns string array, you have to use above code.

Comments

3

String#split returns a String array. You need to use the elements of the returned Array:

String[] strings = k.split("/");
int mm = Integer.parseInt(strings[0]);
int dd = Integer.parseInt(strings[1]);

Comments

2

Or even

   Scanner dates = new Scanner(k);
   dates.useDelimiter("/");
   int mm = dates.nextInt();
   int dd = dates.nextInt();

and then you don't need to parse the integer

Comments

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.