Hi all,

I'm just finishing the code part of an assignment
I think I have everything working as intended with the exception that
After either the prime number or stamp duty methods complete (A & B options)
they don't "flush" the char choice (under the getChoice method )

The vowel counter (Menu option C) completes fine without the extra loop.


From what I can gather the problem is in the line

char getChoice = ' ';

As after running either A or B methods it jumps to "default"
under the switch statement,so it doesn't wait for the new choice?

Could one of you fine people please point me in the right direction?
I'm really close I can feel it!

Thank you in advance
(Code comments/algorithms not yet complete)

import java.util.*;
import java.io.*;

public class assignment1
{

    private static Scanner input = new Scanner(System.in); // Used for taking users' input


    public static void main(String[] args) 
    {
    	char choice = ' ';	// to intialise the variable
    	while (choice != 'X' || choice !='x')  // A menu loop to stop premature program termination
    	{
	      	displayMenu();
	    	choice = getChoice();
	    	processChoice(choice);
    	}
    }

    public static void displayMenu()
    //------------------------------
    // Displays menu: (A) Prime Number Checker
    //                (B) Select Account 2
    //                (C) Deposit to selected account
    //                (X) Exit
    //                Please enter your selection  >>

	{
        System.out.println ( " ----------------------------------");
		System.out.println ( " (A) Prime Number Checker.");
		System.out.println ( " (B) Stamp Duty Calculator.");
		System.out.println ( " (C) Vowel Counter.");
		System.out.println ( " (X) Exit  " );
		System.out.println ( " ----------------------------------");
	}

    public static char getChoice()
	//----------------------------
	// Return the first character of the user's keyboard entry.
    {
	System.out.print ("Please enter your selection  >>  ");
	String choice = input.nextLine();
	char getChoice = ' ';
	if( choice.length() > 0 )
	{
		getChoice = choice.charAt(0);
	}
		return getChoice;
    }

    public static void processChoice(char choice_)
    // Performs the required function.
    // Does nothing if the choice_ is invalid.
  
    {
	switch (choice_)
	{
    	case 'A':
        case 'a':
                     primeNumberChecker(); // Calls Prime Number Method
                     break;

            case 'B':
            case 'b':
                     stampDutyCalculator();  // Calls Stamp Duty Method
                     break;

            case 'C':
            case 'c':
                     vowelCounter();  // Calls Vowel Counting Method
                     break;

            case 'X':
            case 'x':
                     System.out.println ("Exiting the program... thankyou");
                     System.exit(0);	// Exits the program
                     break;

            default:	// Default message for invalid char
                    System.out.println("Error! " + choice_ +
                                       " is not a valid menu option");
        }
    }


	public static void primeNumberChecker()

{
      // prompt for user input
      System.out.print("Please enter a number  >>  ");
      int number = input.nextInt();
      boolean isPrime = true;
 
      // test for prime number
 
      for (int i = 2; i < number; i++)
      {
         if ((number % i) == 0)
         {
	    isPrime = false;
            System.out.println(number + " is not a prime number"); // The loop stops here when the number is not prime
            return;
         }
	
 
      }
	isPrime = true;
	System.out.println(number + " is a prime number"); // If the loop continues the number is prime

   }  




    public static void stampDutyCalculator()
    /*	Calculates stamp duty on a purchase price
    *	Up to $20,000 = 1.4% duty
    *	From $20,001 to $115,000 = 2.4% duty
    *	From $115,001 to $870,000 = 6% duty
    *	Greater than $870,000 = 5.5% of total dutiable amount
    */
    
    {
    	double purchase,stamp; 		// Values for input (purchase) and calculation (stamp)
	double tier1Rate = 0.014;	// Rates as specified in the assignment
	double tier2Rate = 0.024;
	double tier3Rate = 0.060;
	double tier4Rate = 0.055;	
    	int tier1 = 20000;		// Tier brackets as specified in the assignment
	int tier2 = 115000;
	int tier3 = 870000;

    	System.out.print("\nPlease enter a purchase value   >>  ");
    	purchase = input.nextDouble();
    	if (purchase > 0 && purchase <= tier1) 
    	{
    		stamp = (purchase*tier1Rate);
    		System.out.println("The stamp duty payable is : " + stamp + "\n\n");
    	}
    	else if (purchase > tier1 && purchase <= tier2)
    	{
    		stamp = (tier1*tier1Rate) + ((purchase-tier1)*tier2Rate);
    		System.out.println("The stamp duty payable is : " +stamp + "\n\n");
    	}
    	else if (purchase > tier2 && purchase <= tier3)
    	{
    		stamp = (tier1*tier1Rate) + ((tier2-tier1)*tier2Rate) + ((purchase-(tier1+tier2))*tier3Rate);
    		System.out.println("The stamp duty payable is : " +stamp + "\n\n");
    	}
    	else if (purchase > tier3)
    	{
    		stamp = (purchase*tier4Rate);
    		System.out.println("The stamp duty payable is : " +stamp + "\n\n");
    	}
    }

    public static void vowelCounter()
    {
    	System.out.println("\nPlease enter a phrase to check");
    	String phrase = input.nextLine();
    	int count = 0;	// To initialise the variable
    	
    	for (int a = 0; a < phrase.length(); a++)	// A loop created to start at the first char
    												// and finish at the last char, moving along by 1 char
    	{
    		char b = phrase.charAt(a);	// A variable created to test if the char in the string is a vowel
    		
    		if (b == 'a' || b == 'e' || b == 'i' || b == 'o' || b == 'u')
    		{
    			count++;	// Adds to the vowel count for each time b is either a,e,i,o,u
    		}
    		
    	}
    	
    	System.out.println("The total number of vowels are : " + count);
    }


}

I can't see the problem after a quick look. Put lots of print statements into your code so you can see the exact sequence of execution and variable updates that lead to the problem.

Hi James thanks for your reply,

I put a few print msg's in the code and it seems that the
line

String choice = input.nextLine();

is being completely ignored by the program after the initial menu choice
when it goes back to loop to the menu, instead of pausing and waiting for input
it simply thinks it already has the input and then returns a blank char with it's
return statement. It only does this for A&B from the menu, so i'm really
struggling to understand why on earth it would do this.

Is there another way I could rewrite this to see perhaps?

FYI This is the output from my terminal

[nate@nate java]$ java assignment1
 ----------------------------------
 (A) Prime Number Checker.
 (B) Stamp Duty Calculator.
 (C) Vowel Counter.
 (X) Exit  
 ----------------------------------

Please enter your selection  >>  a
Please enter a number  >>  2
2 is a prime number
 ----------------------------------
 (A) Prime Number Checker.
 (B) Stamp Duty Calculator.
 (C) Vowel Counter.
 (X) Exit  
 ----------------------------------

Please enter your selection  >>  Error!   is not a valid menu option


 ----------------------------------
 (A) Prime Number Checker.
 (B) Stamp Duty Calculator.
 (C) Vowel Counter.
 (X) Exit  
 ----------------------------------

Please enter your selection  >>

Probably this:
nextInt() takes the "2" from the console input, leaving the following carriage-return in the input buffer. So next time round your nextLine(); takes everything up to the CR - ie nothing. After taking an int or whatever you need to use an extra nextLine(), or some other call, to clear the rest of that line from the input buffer.
If you had use print statements like I suggested you would have seen this for yourself.

I had attempted to put in print statements to the best of my abilities
and actually felt that I was doing well enough with java so far..

I feel that you are requesting an apology for my lack of understanding
of java? I am very much still learning java (hence me studying it)..

Having said that I'm going to attempt to work out where i would
have to insert another nextLine()

Thanks for your assistance thus far.

After posting that I've managed to work out that to clear the Input buffer
was to change

String choice = input.nextLine();

to

String choice = input.next();

Solved, thanks

Please don't misunderstand - I was just trying to help, not criticising, and certainly not expecting an apology!
You will see a number of us repeatedly posting advice to use more print statements for debugging because so many beginners don't use this technique enough, and thus have great difficulty debugging. I'm not just picking on you here!
As for the nextLine() - I suggest that you define a standard behaviour for all your code that uses the scanner, eg "all methods that use the scanner will leave it at the start of the next line". Thus methods that end with a nextLine() are OK, but methods that end with a nextInt() or whatever are responsible for adding an extra nextLine() in order to leave the scanner in the standard state. That way it's clear who has to do what.

ps: we parallel posted there! Yes, instead of the way I suggested above you can alternatively have a standard of not using nextLine() and consistently ignoring carriage-returns. The imnportant thing is to have a standard and stick to it.

I understand what you mean, I had done the debugging silently (putting in print statements to see at what step things were skipped or what have you)
and the step i missed was to print the "choice" char to screen so I could see that it
was still carrying over the previous scanner object, I'll know for future.

Thank you for all of your prompt replies James, it is very much appreciated :)
Hopefully one day I might be able to add to this board myself.

Hopefully one day I might be able to add to this board myself.

Hopefully you will! Nobody is so new that they have nothing to contribute, and nobody (except possibly ~s.o.s~) is so knowledgeable that they have nothing to learn.
Time to mark this thread solved. If/when you hit your next problem its best to start a new thread with an appropriate title.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.