Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 3 of 3

Thread: Having to press 'ENTER' twice

  1. #1
    Member
    Join Date
    Aug 2020
    Posts
    42
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Question Having to press 'ENTER' twice

    Hello, I am working on a, you could say, a small project where the user is able to create of list of movies they'd like and add, remove, replace it, etc. There are only a limited number of options within the program. The only problem currently that I have is that I have to press the 'ENTER' key twice in order for the program to continue. I've already tried reading up on the difference between the Scanner class's '.next()' and '.nextLine()' and I get that '.next()' reads up until there's a whitespace, while '.nextLine()' reads the whole line, then moving on to the next. I believe my problem to be in my main class, which would be the second code I will paste below.

    NOTE: Once again I managed to understand what was wrong after taking a break and giving it some time in my head. The problem was in the main class, and I'll post a third code bit with the solution and pointing at what was the problem.

    I have two classes, one for the commands, and a main where everything is executed. Here they are below:

    MovieCommands Class
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;
    import java.util.ArrayList;
     
    public class MovieCommands {
     
    	public ArrayList<String> movieList = new ArrayList<String>();
     
    	public ArrayList<String> getMovieList(){
    		return movieList;
    	}
     
    	public void addMovieTitle(String movieTitle) {
    		if(!(movieList.contains(movieTitle))) {
    			movieList.add(movieTitle);
    			System.out.println(movieTitle + " was added.");
    		}else
    			System.out.println(movieTitle + " is already in the list.");
    	}
     
    	public void printMovieList() {
    		if(movieList.size()==0)
    			System.out.println("\nThere are no movie titles in this list.");
    		else {
    			System.out.println("\nMovieList:");
    			for(int i=0; i<movieList.size(); i++) {
    				System.out.println((i+1) + ". " + movieList.get(i));
    			}
    		}
    	}
     
    	private int findMovieTitle(String movieTitle) {
    		return movieList.indexOf(movieTitle);
    	}
     
    	public void searchMovieTitle(String movieTitle) {
    		if(findMovieTitle(movieTitle)!=-1)
    			System.out.println(movieTitle + " found.");
    		else
    			System.out.println(movieTitle + " not found.");
    	}
     
    	public void removeMovieTitle(String movieTitle) {
    		if(findMovieTitle(movieTitle)!=-1) {
    			movieList.remove(findMovieTitle(movieTitle));
    			System.out.println(movieTitle + " was removed.");
    		} else
    			System.out.println(movieTitle + " does not exist, and thus, was not removed.");
    	}
     
    	public void replaceMovieTitle(String oldTitle, String newTitle) {
    		int index = findMovieTitle(oldTitle);
    		if(index != -1) {
    			movieList.remove(index);
    			movieList.add(index, newTitle);
    			System.out.println(oldTitle + " has been replaced with " + newTitle + ".");
    		} else
    			System.out.println(oldTitle + " does not exist in list.");
    	}
     
    	public void endProgram() {
    		System.out.println("\nShutting down....\nGoodbye.");
    		System.exit(0);
    	}
     
    	public void printOntoFile() {
    		try {
    			FileWriter fw = new FileWriter("MovieList.txt");
    			PrintWriter pw = new PrintWriter(fw, false);
    			pw.println("Movie List:");
    			for(int i=0; i<movieList.size(); i++) {
    				pw.println(movieList.get(i));
    			}
    			pw.close();
    			System.out.println("\nFile created.");
    		} catch (IOException e) {
    			System.out.println("Oops, something went wrong.");
    			e.printStackTrace();
    			System.exit(0);
    		}
    	}
     
    	public void readsIntoArrayList() {
    		File file = new File("MovieList.txt");
    		Scanner input = null;
     
    		try {
    			input = new Scanner(file);
    			input.nextLine();//read in the header and do nothing with it
    			while(input.hasNextLine()) {
    				movieList.add(input.nextLine());
    			}
    		} catch (FileNotFoundException e) {
    			System.out.println("No file to read from found.\n");
    			//e.printStackTrace();		//<--- outputs an error message to console
    			//System.exit(0);
    		}
     
    	}
     
    }//end MovieCommands class

    Main Class:
    import java.util.Scanner;
     
    public class MovieMain {
     
    	private static Scanner sc = new Scanner(System.in);
    	private static MovieCommands movies = new MovieCommands();
     
    	public static void main(String[] args) {
     
    		movies.readsIntoArrayList();
    		System.out.println("Welcome to the movie list application.\nSelect an action from one of the options below:");
    		while(true) {
    			printOptions();
    			System.out.print("Enter your choice: ");
    			if(sc.hasNextInt()) {
    				int option = sc.nextInt();
    				if(option >= 0 && option <=6)
    					optionExecution(option);
    				else
    					System.out.println("\nValue is out of range. Please try again.");
    			} else {
    				sc.nextLine();
    				System.out.println("\nInvalid value. Please try again.");
    			}
    		}
     
    	}//end main
     
    	public static void printOptions() {
    		System.out.println("\n0 - End program.");
    		System.out.println("1 - Add a movie title to the list.");
    		System.out.println("2 - Print movie title list.");
    		System.out.println("3 - Search for a movie title within the list.");
    		System.out.println("4 - Remove a movie title from the list.");
    		System.out.println("5 - Replace a movie title within the list.");
    		System.out.println("6 - Print the movie list onto a file.");
    	}
     
    	public static void optionExecution(int optionNum) {
    		switch(optionNum) {
    		case 0:
    			sc.close();
    			movies.endProgram();
    		case 1:
    			System.out.print("\nEnter the movie title you would like to add: ");
    			sc.nextLine();
    			movies.addMovieTitle(sc.nextLine());
    			break;
    		case 2:
    			movies.printMovieList();
    			break;
    		case 3:
    			System.out.print("\nEnter the movie title you are searching for: ");
    			sc.nextLine();
    			movies.searchMovieTitle(sc.nextLine());
    			break;
    		case 4:
    			System.out.print("\nEnter the movie title you would like to remove: ");
    			sc.nextLine();
    			movies.removeMovieTitle(sc.nextLine());
    			break;
    		case 5:
    			System.out.print("\nEnter the movie title you would like to replace: ");
    			sc.nextLine();
    			String oldTitle = sc.nextLine();
    			System.out.print("\nEnter the movie title you would like to replace with: ");
    			String newTitle = sc.nextLine();
    			movies.replaceMovieTitle(oldTitle, newTitle);
    			break;
    		case 6:
    			movies.printOntoFile();
    			System.out.println("Movie list saved onto 'MovieList.txt' file.");
    			break;
    		}
    	}//end optionExecution
     
    }//end class

    Main Class fixed:
    import java.util.Scanner;
     
    public class MovieMain {
     
    	private static Scanner sc = new Scanner(System.in);
    	private static MovieCommands movies = new MovieCommands();
     
    	public static void main(String[] args) {
     
    		movies.readsIntoArrayList();
    		System.out.println("Welcome to the movie list application.");
    		while(true) {
    			printOptions();
    			String optionInput = sc.nextLine();
    			boolean hasInt = optionValidation(optionInput);
    			if(hasInt) {
    				int num = Integer.valueOf(optionInput);
    				if(num >= 0 && num <=6)
    					optionExecution(num);
    				else {
                                            //sc.nextLine()      <--- This bit here was the issue whenever the user woud input an incorrect value, as the scanner would look for another 'ENTER' key/\n due to this
    					System.out.println("\n" + "(" + num + ")" + " is not a valid value. Please try again.");
    				}
    			} else {
                                    //sc.nextLine()      <--- This bit here was the issue whenever the user woud input an incorrect value, as the scanner would look for another 'ENTER' key/\n due to this
    				System.out.println("\n" + "(" + optionInput + ")" + " is not a valid input. Please try again.");
    			}
    		}
     
    	}//end main
     
    	public static void printOptions() {
    		System.out.println("\nSelect an action from one of the options below:");
    		System.out.println("0 - End program.");
    		System.out.println("1 - Add a movie title to the list.");
    		System.out.println("2 - Print movie title list.");
    		System.out.println("3 - Search for a movie title within the list.");
    		System.out.println("4 - Remove a movie title from the list.");
    		System.out.println("5 - Replace a movie title within the list.");
    		System.out.println("6 - Print the movie list onto a file.");
    		System.out.print("Enter your choice:");
    	}
     
    	public static void optionExecution(int optionNum) {
    		switch(optionNum) {
    		case 0:
    			sc.close();
    			movies.endProgram();
    		case 1:
    			System.out.print("\nEnter the movie title you would like to add: ");
    			movies.addMovieTitle(sc.nextLine());
    			break;
    		case 2:
    			movies.printMovieList();
    			break;
    		case 3:
    			System.out.print("\nEnter the movie title you are searching for: ");
    			movies.searchMovieTitle(sc.nextLine());
    			break;
    		case 4:
    			System.out.print("\nEnter the movie title you would like to remove: ");
    			movies.removeMovieTitle(sc.nextLine());
    			break;
    		case 5:
    			System.out.print("\nEnter the movie title you would like to replace: ");
    			String oldTitle = sc.nextLine();
    			System.out.print("\nEnter the movie title you would like to replace with: ");
    			String newTitle = sc.nextLine();
    			movies.replaceMovieTitle(oldTitle, newTitle);
    			break;
    		case 6:
    			movies.printOntoFile();
    			System.out.println("Movie list saved onto 'MovieList.txt' file.");
    			break;
    		}
    	}//end optionExecution
     
    	public static boolean optionValidation(String input) {
    		boolean isAnInt = false;//used to check in the for loop below if the SINGLE String char is at least an int by checking if it may be a num 0-9
    		if(input.length()>1 || input.isEmpty()) {
    			return false;
    		}else {
    			for(int i=0; i<10; i++) {
    				if(input.equals(String.valueOf(i)))
    					isAnInt = true;
    			}
    			return isAnInt;
    		}
    	}
     
     
    }//end class
    Last edited by HyperRei; July 30th, 2021 at 04:58 PM. Reason: New Issue on Same program

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    On vacation
    Posts
    24,712
    Thanks
    57
    Thanked 2,678 Times in 2,628 Posts

    Default Re: Error message printing twice

    It would be helpful for debugging if the value returned by the nextLine method were saved in a variable and printed out so the user could see what the Invalid value was.

    I suspect the problem is with the Scanner class and the mixing of the use of the next... and nextLine methods.
    It is explained here: https://www.geeksforgeeks.org/why-is...ext-functions/
    If you don't understand my answer, don't ignore it, ask a question.

  3. The Following User Says Thank You to Norm For This Useful Post:

    HyperRei (July 29th, 2021)

  4. #3
    Member
    Join Date
    Aug 2020
    Posts
    42
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Default Re: Error message printing twice

    Thank you very much for the suggestion. The thought of printing out the invalid value back to the user as also a helpful way to debug didn't occur to me. I'll keep this in mind moving forward with other projects. Thank you.

Similar Threads

  1. I keep getting an error message but I don't know how to fix this!
    By mpagudelo in forum What's Wrong With My Code?
    Replies: 2
    Last Post: September 12th, 2013, 01:56 AM
  2. [SOLVED] Getting error message and can not figure it out.
    By GoPredsGo in forum What's Wrong With My Code?
    Replies: 3
    Last Post: July 10th, 2013, 04:33 AM
  3. Need help with error message!!
    By Rick Sebastian in forum What's Wrong With My Code?
    Replies: 14
    Last Post: March 25th, 2013, 10:24 AM
  4. Strange error message
    By javapenguin in forum What's Wrong With My Code?
    Replies: 7
    Last Post: January 11th, 2011, 02:03 PM
  5. help with a error message
    By JavaNoob82 in forum What's Wrong With My Code?
    Replies: 6
    Last Post: January 23rd, 2010, 02:56 PM

Tags for this Thread