Reputation: 15
I try to create a program in Java that asks user for time (hh:mm:ss format). I have 2 problems:
1) When running the program, as soon as I enter data from the keyboard, the program throws java.lang.NullPointerException
.
I am not sure how to fix it. I tried and created global variable for an array but it didn't fix the issue.
2) If I change code.split(":")
to code.split(".")
program is throwing a MissingColonException
loop infinitely.
How can I stop it? I did not include code for exceptions, as I thought the issue is not there.
import java.util.Scanner;
public class CatchExceptionClock {
static String [] time;
public static void main (String[] args) {
String code = "";
Scanner scan = new Scanner (System.in);
System.out.print ("Please enter time. The input data should have the format hh:mm:ss");
code = scan.nextLine();
while (!code.equals ("STOP")) {
try {
getInput(code);
checkHour (time [0]);
checkMinutes (time [1]);
checkSeconds (time [2]);
} catch (NumberFormatException exception) {
System.out.println ("Number is not numeric: " + ". You entered: " + code);
System.out.println ("");
} catch (MissingColonException d) {
System.out.println (d.getMessage()+ ". You entered: "+ code);
System.out.println ("0");
} catch (HourException o) {
System.out.println (o.getMessage()+ ". You entered: "+ code);
System.out.println ("");
} catch (MinutesException e) {
System.out.println (e.getMessage()+ ". You entered: "+ code);
System.out.println ("");
} catch (SecondsException a) {
System.out.println (a.getMessage()+ ". You entered: "+ code);
System.out.println ("");
}
}
System.out.print ("Enter code (STOP to quit): ");
code = scan.nextLine();
}
public static String[] getInput(String code) {
String [] time = code.split(":");
if (time.length ==3)
return time;
else
throw new MissingColonException("The input is missing a colon.The input data should have the format hh:mm:ss ");
}
public static void checkHour (String time) {
int hour = Integer.parseInt (time);
if (hour <0 || hour >24)
throw new HourException("The hour should be a value between 0 and 24 ");
}
public static void checkMinutes (String time) {
int minutes = Integer.parseInt (time);
if (minutes <0 || minutes >60)
throw new MinutesException("Minutes should be a value between 0 and 60 ");
}
public static void checkSeconds (String time) {
int seconds = Integer.parseInt (time);
if (seconds <0 || seconds >60)
throw new SecondsException("Seconds should be a value between 0 and 60 ");
}
}
Upvotes: 0
Views: 71
Reputation: 12819
In your getInput
method, you create a local array time
that shadows the static version. You want:
time = code.split(":");
instead of:
String[] time = code.split(":");
Also none of your methods modify code
, so unless the user inputs the stop condition on the first run, the loop will always be infinite. You need to add a
code = scan.nextLine();
at the end of your loop
Upvotes: 1