I am writing an appointment program in Java and am coming across an error which is
Exception in thread "main" java.lang.NumberFormatException: For input string : ""
for the following lines :
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:470)
at java.lang.Integer.parseInt(Integer.java:499)
at AppointmentNew.main(AppointmentNew.java:24)
The program is going through once, but once it gets to the end of its first run it gives me those errors.... For instance when I run the program as follows : I make the choice of "1" to make a new appointment, I then enter the date of my new appointment "mm/dd/yyyy", then I add an appointment description, and lastly I enter the type "Once, Daily, or Monthly". After that finishes it should start back over with the very first line of "Make Choice (1: New, 2: Print Range, 3: Print All, quit):" But instead it gives me the errors I described above...
Here is my code I have.
import java.util.*;
public class AppointmentNew
{
public static void main (String[] args)
{
ArrayList<String> list = new ArrayList<String>();
Scanner stdin = new Scanner(System.in);
String choice = "";
int choiceNum = 0;
String date = "";
String descrip = "";
int type = 0;
String typeChose = "";
System.out.println("Welcome to Appointment App!\n");
System.out.println("\t============================\n");
do
{
System.out.print("\tMake Choice ( 1: New, 2: Print Range, 3: Print All, quit): ");
choice = stdin.nextLine();
choiceNum = Integer.parseInt(choice);
if (choiceNum == 1)
{
System.out.print("\n\n\tEnter New Appointment Date in mm/dd/yyyy format: ");
date = stdin.nextLine();
System.out.print("\n\n\tEnter New Appointment Description: ");
descrip = stdin.nextLine();
System.out.print("\n\n\tEnter Type (1 = Once, 2 = Daily, 3 = Monthly): ");
type = stdin.nextInt();
if (type == 1)
{
Once once = new Once(date, descrip);
typeChose = "One-Time";
}
else if (type == 2)
{
Daily daily = new Daily(date, descrip);
typeChose = "Daily";
}
else
{
Monthly monthly = new Monthly(date, descrip);
typeChose = "Monthly";
}
String stringToAdd = "";
stringToAdd = ("\n\n\tNew " + typeChose + " Appointment Added for " + date + "\n");
list.add(stringToAdd);
System.out.println(stringToAdd);
System.out.println("\t============================\n");
}
if (choiceNum == 2)
{
System.out.print("\n\n\tEnter START Date in mm/dd/yyyy format: ");
String lowDate = stdin.nextLine();
System.out.print("\n\n\tEnter END Date in mm/dd/yyyy format: ");
String highDate = stdin.nextLine();
for(int i = 0; i < list.size(); i++)
{
int dateSpot = list.get(i).indexOf(" ");
if (list.get(i).compareTo(lowDate) <= 0 && list.get(i).compareTo(highDate) >= 0)
{
System.out.println(list.get(i));
}}
}
if (choiceNum == 3)
{
for(int i = 0; i < list.size(); i++)
{
System.out.println(list.get(i));
}
}
}while (choice != "quit");
}
}
Any help would be great!
You need to add another call to nextLine() after this statement here:
type = stdin.nextInt();
// ED: stdin.nextLine();
This is because, when you grab an int from the Scanner, it doesn't consume the '\n' character that gets put on the input stream when the user hits enter.
Thus, when stdin.nextLine() is called again, the String "" is returned (everything not yet processed up to the next '\n' character), and Integer.parseInt doesn't know how to handle that, so you get an error.
Surround the code with an if statement to check if the value is not quit before trying to Parse it.
Related
I try to check if characters in a firstname String contain at least 1 digit, if yes ask to the user to input it again and then going back to the loop and check again but with a GoTo break it only works the first time and won't loop it again. Oh and I do this from a method with a String array of more than only a first name in it. Isn't the break GoTo supposed to bring me back to my label and then do the loop over again looking for a digit?
public static void main(String[] args) {
infoInputGathering();
}
public static String[] infoInputGathering(){
String[] infos = new String[3]; // Declaration of the infos String array
boolean isStringOnly;
char[] characterChecker;
Scanner input = new Scanner(System.in); // Creation of the Scanner object input
// Asking the user to input their first name and stores it in a String Array info[0]
System.out.print("Enter your first name: ");
infos[0] = input.next();
characterChecker = infos[0].toCharArray();
firstname:
for (int c = 0 ; c<=characterChecker.length ; ++c ) {
if (Character.isDigit(characterChecker[c])) {
System.out.println("A first name should not contain any number...");
System.out.print("Enter your first name without a number: ");
infos[0] = input.next();
characterChecker = infos[0].toCharArray();
Break firstname;
}
}
Final Full Code I came up with with Ali's help on this part
import java.util.Scanner;
import java.util.ArrayList;
public class InfiniteInfoGatheringUntilStop {
public static void main(String[] args) {
int iterationsCounter = 0; // Declares/Initiate a counter for the loops
Scanner input = new Scanner(System.in); // Creation of the Scanner object input
ArrayList<String> names = new ArrayList<String>(); // Creates an ArrayList for the names inputs
ArrayList<String> birth = new ArrayList<String>(); // Creates an ArrayList for the date of birth inputs
ArrayList<String> gpa = new ArrayList<String>(); // Creates an ArrayList for the GPA inputs
while(true){ // Always true loop unless break out on if conditions
System.out.print("Enter your name: ");
names.add(input.next());
//Code to check if there are numerical character in the String of the listArray inputted
char[] characterChecker = names.get(iterationsCounter).toCharArray(); //Declare and initiates an array of character from the ArrayList names(iterationsCounter)
int c = 0;
while(true){ // Loop to check every character and asks for a retype if detects one character as numerical
if(Character.isDigit(characterChecker[c])){
System.out.println("A first name should not contain any number...");
System.out.print("Enter your first name without a number: ");
names.set(iterationsCounter,input.next());
characterChecker = names.get(iterationsCounter).toCharArray();
c = 0;
}
else {
c++;
}
if(c == characterChecker.length){
break;
}
}
if(names.get(iterationsCounter).equalsIgnoreCase("stop")){ //Checks if stop has been typed, breaks in that case but erases previous ArrayLists of this cycle
names.remove(iterationsCounter);
break;
}
System.out.print("Enter your date of birth in this format AAAAmmdd: ");
birth.add(input.next());
characterChecker = birth.get(iterationsCounter).toCharArray(); //Declare and initiates an array of character from the ArrayList names(iterationsCounter)
c = 0;
while(true){ // Loop to check every character and asks for a retype if detects one character as letter
if(characterChecker.length != 8){ // Checks for a maximum length of 8 characters
System.out.println("A date of birth in the right format (AAAAmmdd) please...");
System.out.print("Reenter your date of birth again (AAAAmmdd): ");
birth.set(iterationsCounter,input.next());
characterChecker = birth.get(iterationsCounter).toCharArray();
}
else if(Character.isLetter(characterChecker[c])){ //checkes if there are letters in the characters
System.out.println("A date of birth in the right format (AAAAmmdd) please...");
System.out.print("Reenter your date of birth again (AAAAmmdd): ");
birth.set(iterationsCounter,input.next());
characterChecker = birth.get(iterationsCounter).toCharArray();
c = 0;
}
else {
c++;
}
if(c == characterChecker.length){ //breaks when c = to the length meaning all characters have been checked through the loop
break;
}
}
if(birth.get(iterationsCounter).equalsIgnoreCase("stop")){ //Checks if stop has been typed, breaks in that case but erases previous ArrayLists of this cycle
names.remove(iterationsCounter);
birth.remove(iterationsCounter);
break;
}
System.out.print("Enter your GPA in 0.0 format: ");
gpa.add(input.next());
characterChecker = gpa.get(iterationsCounter).toCharArray(); //Declare and initiates an array of character from the ArrayList names(iterationsCounter)
c = 0;
while(true){ // Loop to check every character and asks for a retype if detects one character as letter
if(characterChecker.length != 3){ // Checkes for a maximum length of 8 characters
System.out.println("A GPA in the right format please (0.0)...");
System.out.print("Reenter your GPA please: ");
gpa.set(iterationsCounter,input.next());
characterChecker = gpa.get(iterationsCounter).toCharArray();
}
else if(Character.isLetter(characterChecker[c])){ //checks if there are digits in the characters
System.out.println("A GPA in the right format please (0.0)...");
System.out.print("Reenter your GPA: ");
gpa.set(iterationsCounter,input.next());
characterChecker = gpa.get(iterationsCounter).toCharArray();
c = 0;
}
else {
c++;
}
if(c == characterChecker.length){ //breaks when c = to the length meaning all characters have been checked through the loop
break;
}
}
if(gpa.get(iterationsCounter).equalsIgnoreCase("stop")){ //Checks if stop has been typed, breaks in that case but erases previous ArrayLists of this cycle
names.remove(iterationsCounter);
birth.remove(iterationsCounter);
gpa.remove(iterationsCounter);
break;
}
iterationsCounter++; // Incrementes the counter if a full loop is done
}
// Prints the results
System.out.println("Number of valid inputs before you got exhausted: " + iterationsCounter);
System.out.println("====================================================================================");
//A loop to print the content of the 3 ListArrays
for(int arrayLoc = 0; arrayLoc < iterationsCounter; arrayLoc++){
System.out.println((arrayLoc+1) + "-\t" + names.get(arrayLoc) +
"\t\t" + birth.get(arrayLoc) +
"\t\t" + gpa.get(arrayLoc));
}
}
}
You can write your code with while loop like this:
import java.util.Scanner;
public class Test{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] infos = new String[3];
char[] characterChecker;
System.out.print("Enter your first name: ");
infos[0] = input.next();
characterChecker = infos[0].toCharArray();
int c = 0;
while(true){
if (Character.isDigit(characterChecker[c])){
System.out.println("A first name should not contain any number...");
System.out.print("Enter your first name without a number: ");
infos[0] = input.next();
characterChecker = infos[0].toCharArray();
c = 0;
}
else
c++;
if(c == characterChecker.length)
break;
}
System.out.println("Correct Name");
}
}
If c is equal to characterChecker.length, ie in the name, there is no number, then it is correct and we break loop and print Correct Name.
So I am completely new to java, and I want to create a code to accept string inputs from a user, and store it into an array. After this in the next statement, I will type a value into the terminal, and I want the code to compare my string input to one of the strings in the array and print available on the terminal when the string is available and vice versa. The first part of my code was right (hopefully) but I had a problem in comparing the strings. I feel it doesn't check the strings with my input in the code. Here is my code, Could anyone please help me with this? Thank you so much.
import java.util.Scanner;
class Course {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a[] = new String[20] //assuming max 20 strings
System.out.println("Enter no. of courses");
int no_of_courses = sc.nextInt(); // number of strings
if (no_of_courses <= 0)
System.out.println("Invalid Range");
else {
System.out.println("Enter course names:");
for (int i = 0; i < no_of_courses; i++) {
a[i] = sc.next(); //accepting string inputs
}
System.out.println("Enter the course to be searched:");
String search = sc.next() //entering a string to search
for (int i = 0; i < no_of_courses; i++) {
if (a[i].equals(search)) //I feel the problem is here
System.out.println(search + "course is available");
break;
else
System.out.println(search + "course is not available");
}
}
}
}
I expect the output to be
<string> course is available
when my string matches a string in the array and
<string> course is not available
when my entered string doesn't match a string in the array
But there is no output :(
I have modified your code and commented on line where it need to be explained. check it carefully.
import java.util.Scanner;
class Course {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter no. of courses");
int no_of_courses = sc.nextInt(); // number of strings
String a[] = new String[no_of_courses]; // do not assume when you have proper data.
if (no_of_courses <= 0)
System.out.println("Invalid Range");
else {
System.out.println("Enter course names:");
for (int i = 0; i < no_of_courses; i++) {
a[i] = sc.next(); // accepting string inputs
}
System.out.println("Enter the course to be searched:");
String search = sc.next(); // entering a string to search
boolean flag = false;
for (int i = 0; i < no_of_courses; i++) {
if (a[i].equals(search)) // I feel the problem is here
{
flag = true;//do not print here. just decide whether course is available or not
break;
}
}
//at the end of for loop check your flag and print accordingly.
if(flag) {
System.out.println(search + "course is available");
}else {
System.out.println(search + "course is not available");
}
}
}
}
class Course {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String a[] = new String[20] ; //assuming max 20 strings
System.out.println("Enter no. of courses");
int no_of_courses = sc.nextInt(); // number of strings
if(no_of_courses <= 0)
System.out.println("Invalid Range");
else
{
System.out.println("Enter course names:");
for(int i=0 ; i < no_of_courses ; i++)
{
a[i] = sc.next(); //accepting string inputs
}
System.out.println("Enter the course to be searched:");
String search = sc.next() ; //entering a string to search
boolean found = false;
for(int i = 0 ; i < no_of_courses ; i++)
{
if(a[i].equalsIgnoreCase(search)) //I feel the problem is here
{
**found = true;**
break;
}
}
if(found) {
System.out.println(search+ "course is available");
}else {
System.out.println(search+ "course is not available");
}
}
}
}
This is really a good effort and you almost got it. So just a couple of things
Since you are inputting the number of courses, just use that value to initialise your array (it's just a good practice to get into to try not initialise things before you actually need them).
If you are doing String comparisons and case sensitivity does not matter, rather use .equalsIgnoreCase(String)
To solve your problem, you just needed a boolean variable to indicate whether or not you had found a match. Initially this would be FALSE (no match found) and you would run through your array until a match is found. Once found this would be flagged TRUE and you'd breakout your loop (which you correctly did).
Only once out your loop, you'd print out whether you found a match.
Have a look:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter no. of courses");
int no_of_courses = sc.nextInt(); // number of strings
if (no_of_courses <= 0) {
System.out.println("Invalid Range");
} else {
String a[] = new String[no_of_courses];
System.out.println("Enter course names:");
for (int i = 0; i < a.length; i++) {
a[i] = sc.next(); //accepting string inputs
}
System.out.println("Enter the course to be searched:");
String search = sc.next(); //entering a string to search
boolean courseFound = Boolean.FALSE;
for(int i = 0; i < a.length; i++) {
if (a[i].equalsIgnoreCase(search)) {
courseFound = Boolean.TRUE;
break;
}
}
if(courseFound) {
System.out.println(search + "course is available");
} else {
System.out.println(search + " course is not available");
}
}
}
Oh, just for interest (and when you start working with some more advanced constructs), you could always just use stream, which was introduced in Java 8. It'll trim down 12 lines to 5...
if(Arrays.stream(a).anyMatch(i -> i.equalsIgnoreCase(search))) {
System.out.println(search + " course is available");
} else {
System.out.println(search + " course is not available");
}
I noticed a few things - Does your program run to the end? When i copy/pasted into my ide i noticed a few missing semi-colons, and like Yhlas said, your last if/else statement syntax is incorrect.
And this doesn't have anything to do with whether or not your program will give you the right answer, but your last loop will print over and over again because it will check each element in a, and each time it loops and finds a mismatch it will print something out
So the problem that I am currently running into is that the statement "Enter your command (reverse, replace first, replace last, remove all, remove)" is printing twice after I go through all the steps.
What I believe is happening is the loop is executing twice but I don't know why. Any help would be appreciated in solving this problem. Sorry in advance if my code formatting is bad still learning how to properly format.
import java.util.Scanner;
public class StringChangerenter {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
// Output Variables
String userInput = "";
// Variables
String removeChar = "", removeAllChar = "";
int removeIndex = 0;
// First Output
System.out.println("Enter the string to be manipulated");
userInput = keyboard.nextLine();
String command = "";
// While loop
while (!command.equalsIgnoreCase("quit")) {
// Output
System.out.println("Enter your command (reverse, replace first, replace last, remove all, remove)");
command = keyboard.nextLine();
if (command.equalsIgnoreCase("remove")) {
System.out.println("Enter the character to remove");
removeChar = keyboard.nextLine();
int totalCount = 0;
for (int j = 0; j < userInput.length(); j++) {
if (userInput.charAt(j) == removeChar.charAt(0)) {
totalCount = totalCount + 1;
}
}
System.out.println("Enter the " + removeChar
+ " you would like to remove (Not the index - 1 = 1st, 2 = 2nd, etc.):");
removeIndex = keyboard.nextInt();
int currentIndex = 1;
if (removeIndex <= totalCount) {
for (int i = 0; i < userInput.length(); i++) {
if (userInput.charAt(i) == removeChar.charAt(0)) {
if (currentIndex == removeIndex) {
String firstpartOfString = userInput.substring(0, i);
String secondpartOfString = userInput.substring(i + 1, userInput.length());
System.out.println("The new sentence is " + firstpartOfString + secondpartOfString);
userInput = firstpartOfString + secondpartOfString;
break;
} else {
currentIndex = currentIndex + 1;
}
}
}
} else {
System.out.println("Can't find " + removeChar + " occuring at " + removeIndex + " int the string.");
}
// Remove All Code
} else if (command.equalsIgnoreCase("remove all")) {
System.out.println("Enter the character to remove");
removeAllChar = keyboard.next();
String newString = "";
for (int i = 0; i < userInput.length(); i++) {
if (userInput.charAt(i) != removeAllChar.charAt(0)) {
newString = newString + userInput.charAt(i);
}
}
userInput = newString;
System.out.println("The new sentence is " + userInput);
}
// Bracket for while loop
}
}
}
The reason you are getting two entries after you've processed a character, is that you have not fully read the line containing the character.
Specifically, you use keyboard.nextInt(); in the upper branch, and keyboard.next(); in the lower branch. While these read the next integer and character, respectively, they do not process the end of line marker.
Then when you reach the top of the loop, you call keyboard.nextLine() which processes whatever characters occurred after the int (or character, in the remove all case) until the end of line marker. With the expected user input, that's just an empty string.
To fix this, you need to ensure you read all the way through the keyboard.nextLine() in the cases where you are reading only integers, or a single character.
what is happening is, the condition for you while loop is
while (!command.equalsIgnoreCase("quit"))
which in english mean, as long as command is not equal to "quit" then run this loop.
Inside the loop, command is never actually set to "quit". ex if I give input string as "abcde" and ask to remove "c" at position 1.
Then your logic sets command to "remove" here
command = keyboard.nextLine();
and then prints the final value as "abde". Now when the loop ends, command is still "remove" and hence the loop executes again.
A possible solution is to explicitly ask the user if he wants to retry using a do while loop. Also just a tip, i see you have used nextInt. It is advisable to use a nextLine immediately after next int. see this for the reason why: Java Scanner doesn't wait for user input
this is what you code would be if you explicitly took user consent if you want to run any more commands:
public static void main (String[] args) throws java.lang.Exception
{
Scanner keyboard = new Scanner(System.in);
// Output Variables
String userInput = "";
// Variables
String removeChar = "", removeAllChar = "";
int removeIndex = 0;
// First Output
System.out.println("Enter the string to be manipulated");
userInput = keyboard.nextLine();
String command = "";
String retry = "";
// While loop
do {
// Output
System.out.println("Enter your command (reverse, replace first, replace last, remove all, remove)");
command = keyboard.nextLine();
if (command.equalsIgnoreCase("remove")) {
System.out.println("Enter the character to remove");
removeChar = keyboard.nextLine();
int totalCount = 0;
for (int j = 0; j < userInput.length(); j++) {
if (userInput.charAt(j) == removeChar.charAt(0)) {
totalCount = totalCount + 1;
}
}
System.out.println("Enter the " + removeChar
+ " you would like to remove (Not the index - 1 = 1st, 2 = 2nd, etc.):");
removeIndex = keyboard.nextInt();
keyboard.nextLine();
int currentIndex = 1;
if (removeIndex <= totalCount) {
for (int i = 0; i < userInput.length(); i++) {
if (userInput.charAt(i) == removeChar.charAt(0)) {
if (currentIndex == removeIndex) {
String firstpartOfString = userInput.substring(0, i);
String secondpartOfString = userInput.substring(i + 1, userInput.length());
System.out.println("The new sentence is " + firstpartOfString + secondpartOfString);
userInput = firstpartOfString + secondpartOfString;
break;
} else {
currentIndex = currentIndex + 1;
}
}
}
} else {
System.out.println("Can't find " + removeChar + " occuring at " + removeIndex + " int the string.");
}
// Remove All Code
} else if (command.equalsIgnoreCase("remove all")) {
System.out.println("Enter the character to remove");
removeAllChar = keyboard.next();
String newString = "";
for (int i = 0; i < userInput.length(); i++) {
if (userInput.charAt(i) != removeAllChar.charAt(0)) {
newString = newString + userInput.charAt(i);
}
}
userInput = newString;
System.out.println("The new sentence is " + userInput);
}
System.out.println("Do you want to go again?");
retry = keyboard.nextLine();
// Bracket for while loop
}while("yes".equalsIgnoreCase(retry));
}
I write 2 ArrayList type String contains the days and possible times , and I want the user to enter input , then check if the input is not from the array it will show a message that the input is invalid and the user enter again . but the result to my code give me the opposite :( when I enter something outside the array it will accept it
what's wrong with my code??
and please show me the right code :(
package javaapplication19;
import java.util.ArrayList;
import java.util.Scanner;
public class JavaApplication19 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<String> dayArray = new ArrayList<>();
ArrayList<String> timeArray = new ArrayList<>();
dayArray.add("sunday");
dayArray.add("monday");
dayArray.add("tuesday");
dayArray.add("wednesday");
dayArray.add("thursday");
timeArray.add("8am");
timeArray.add("9am");
timeArray.add("10am");
timeArray.add("11am");
timeArray.add("12pm");
timeArray.add("1pm");
timeArray.add("2pm");
timeArray.add("3pm");
timeArray.add("4pm");
System.out.println("please enter day :");
String a1 = input.nextLine();
for (int g = 0; g < dayArray.size(); g++){
if (dayArray.get(g).equals(a1))
System.out.println("invalid day , please enter another day : ");
a1 = input.nextLine();
}
System.out.println("please enter time : ");
String a2 = input.nextLine();
for (int s = 0; s < timeArray.size(); s++) {
if (timeArray.get(s).equals(a2))
System.out.println("invalid time , please enter another time : ");
a2 = input.nextLine();
}
}
}
You can use below code and find change in if condition.
System.out.println("please enter time : ");
String a2 = input.nextLine();
for (int s = 0; s < timeArray.size(); s++) {
if (!timeArray.get(s).equals(a2))
System.out.println("invalid time , please enter another time : ");
a2 = input.nextLine();
}
You can do it like this :
String a1 = input.nextLine();
if (!dayArray.contains(a1))
System.out.println("invalid day , please enter another day : ");
else {
System.out.println("day really nice day");
}
There is no need to iterate over the array. The method contains() does it for you
your code should be like this.
System.out.println("please enter day :");
boolean validDate = false;
while(!validDate){
String a1 = input.nextLine();
if(dayArray.contains(a1)){
System.out.println("invalid day , please enter another day : ");
}else{
validDate=true;
}
}
boolean validHour = false;
System.out.println("please enter a time : ");
while(!validHour){
String a2 = input.nextLine();
if(timeArray.contains(a2)){
System.out.println("invalid time , please enter another time : ");
}else{
validHour=true;
}
}
I did refactor your code and put some comments to easier to follow
Scanner input = new Scanner(System.in);
List<String> dayArray = Arrays.asList("sunday","monday","tuesday","wednesday","thursday");
List<String> timeArray = Arrays.asList("8am","9am","10am","11am","12pm","1pm","2pm","3pm","4pm");
String a1 = "";
String a2 = ""; //Store user input
boolean nextInput = false; // flag indicate we continue or we force user re-enter information
//try to read the day input
while (!nextInput) {
System.out.println("please enter day :");
a1 = input.nextLine();
nextInput = dayArray.contains(a1);
}
//try to read the time input
nextInput = false; //<= reset flag
while(!nextInput) {
System.out.println("please enter time : ");
a2 = input.nextLine();
nextInput = timeArray.contains(a2);
}
System.out.println("day :" + a1);
System.out.println("time :" + a2);
System.out.println("program finished");
input.close(); //close scanner
write like this
System.out.println("please enter day :");
String a1 = input.nextLine();
while (!dayArray.contains(a1)){
System.out.println("invalid day , please enter another day : ");
a1 = input.nextLine();
}
System.out.println("please enter time : ");
String a2 = input.nextLine();
while (!timeArray.contains(a2)){
System.out.println("invalid time , please enter another time : ");
a2 = input.nextLine();
}
I am writing an appointment program in Java and am coming across an error which is as follows :
AppointmentNew.java:68: unreported exception java.text.ParseException; must be caught or declared to be thrown
Date lowDate = sdf.parse(stdin.nextLine());
^
AppointmentNew.java:70: unreported exception java.text.ParseException; must be caught or declared to be thrown
Date highDate = sdf.parse(stdin.nextLine());
^
AppointmentNew.java:77: unreported exception java.text.ParseException; must be caught or declared to be thrown
Date newCurrentDate = sdf.parse(currentDate);
This program is suppose to allow the user to make new appointments, when they do that they are then able to input a date and description (they can do this as many times as they want), after that they can then pick a range of dates for the program to print out (it is suppose to print out the appointments in the date range they provided". This is where my error occurs...
Here is the code I have :
import java.util.*;
import java.text.SimpleDateFormat;
import java.util.Date;
public class AppointmentNew
{
public static void main (String[] args)
{
ArrayList<String> list = new ArrayList<String>();
Scanner stdin = new Scanner(System.in);
String choice = "";
int choiceNum = 0;
String date = "";
String descrip = "";
int type = 0;
String typeChose = "";
System.out.println("Welcome to Appointment App!\n");
System.out.println("\t============================");
do
{
System.out.print("\n\tMake Choice (1: New, 2: Print Range, 3: Print All, 4: Quit) ");
choice = stdin.nextLine();
choiceNum = Integer.parseInt(choice);
if (choiceNum == 1)
{
System.out.print("\n\n\tEnter New Appointment Date in mm/dd/yyyy format: ");
date = stdin.nextLine();
System.out.print("\n\n\tEnter New Appointment Description: ");
descrip = stdin.nextLine();
System.out.print("\n\n\tEnter Type (1 = Once, 2 = Daily, 3 = Monthly): ");
type = stdin.nextInt();
stdin.nextLine();
if (type == 1)
{
Once once = new Once(date, descrip);
typeChose = "One-Time";
}
else if (type == 2)
{
Daily daily = new Daily(date, descrip);
typeChose = "Daily";
}
else
{
Monthly monthly = new Monthly(date, descrip);
typeChose = "Monthly";
}
String stringToAdd = "";
stringToAdd = (date + " : \"" + descrip + "\", " + typeChose);
list.add(stringToAdd);
System.out.println("\n\n\tNew " + typeChose + " Appointment Added for " + date + "\n");
System.out.println("\t============================\n");
}
if (choiceNum == 2)
{
System.out.print("\n\n\tEnter START Date in mm/dd/yyyy format: ");
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date lowDate = sdf.parse(stdin.nextLine());
System.out.print("\n\n\tEnter END Date in mm/dd/yyyy format: ");
Date highDate = sdf.parse(stdin.nextLine());
for(int i = 0; i < list.size(); i++)
{
int dateSpot = list.get(i).indexOf(" ");
String currentDate = list.get(i);
currentDate.substring(0, dateSpot);
Date newCurrentDate = sdf.parse(currentDate);
if (newCurrentDate.compareTo(lowDate) >= 0 && newCurrentDate.compareTo(highDate) <= 0)
{
System.out.println("\n\t" + list.get(i));
}
}
}
if (choiceNum == 3)
{
for(int i = 0; i < list.size(); i++)
{
System.out.println("\n\t" + list.get(i));
}
}
}while (choiceNum != 4);
}
}
The problem is that you're trying to compare a string to a date. What does that even mean?
You should convert the String to a Date (e.g. with SimpleDateFormat) - or ideally, use Joda Time - and then compare the values when you've got them both as the same type.
EDIT: As noted in comments, this isn't what you want either:
SimpleDateFormat sdf = new SimpleDateFormat("mm/dd/yyyy");
mm means minutes in SimpleDateFormat, not months. You want MM/dd/yyyy instead. See the SimpleDateFormat documentation for more details.
currentDate.compareTo(lowDate)
currentDate is String and lowDate is Date. You are trying compareTo on two different things.
Convert currentDate to Date object and then call compareTo();
It is normal, you compare a object of Type Date with a String. Convert your String to a Date with your SimpleDateFormat (or with another format) and you will able to compare both objects.
Date correctCurrentDate = sdf.parse(currentDate);
To avoid to add try/catch in test program, I generally wrote the main method like :
public static void main (String[] args) throws Exception
Of course, for program that run in production, you should use try/catch where you can handle the exception. But it is annoying for a test program.