0
String s= sc.nextLine();  //Suppose I take HH:MM (Time) as string... say 09:45

So s becomes...

s = "09:45";

My question is how do I take HH = 09 and MM = 45 as numbers in integer variable in JAVA.

I have tried ...

String s1[]= s.split(":");

int HH= Integer.valueof(s1[0]);

int MM= Integer.valueof(s1[1]);

But it is giving this exception...

Exception in thread "main" java.lang.NumberFormatException: For input string: "" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at appstreet.Question1.main(Question1.java:42)

ΦXocę 웃 Пepeúpa ツ
  • 43,054
  • 16
  • 58
  • 83
Aditya kumar
  • 76
  • 1
  • 10

2 Answers2

2

Try this (Assuming input format HH:MM):

String s = sc.next(); //instead of nextLine()
int hh = Integer.parseInt(s.substring(0,2));
int mm = Integer.parseInt(s.substring(3));

Or as you did:

String s = sc.next(); //instead of nextLine()
String arr[] = s.split(":");
int hh = Integer.parseInt(arr[0]);
int mm = Integer.parseInt(arr[1]);

See this for difference between next() and nextLine().

Community
  • 1
  • 1
Kaushal28
  • 4,823
  • 4
  • 30
  • 57
0

NumberFormatException means you are trying to convert into an integer something that is not possible to be converter into such...

you have multiple ways to do that anyway:

String s = "09:45";
String s1[] = s.split(":");
int HH = Integer.valueOf(s1[0]);
int MM = Integer.valueOf(s1[1]);
System.out.println(HH);
System.out.println(MM);

// another option using java8
LocalTime lt = LocalTime.parse(s, DateTimeFormatter.ofPattern("HH:mm"));
System.out.println(lt.getHour());
System.out.println(lt.getMinute());
ΦXocę 웃 Пepeúpa ツ
  • 43,054
  • 16
  • 58
  • 83