CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Mar 2005
    Posts
    37

    I don't know what is wrong with my program

    I got this program using nested ifs and it compiles fine but gives me the wrong outcome. The way it is now, when I run the code and the first question shows "Enter the number of years you have been playing, and I enter 10, and then I hit the Enter key and then the next question comes up, but the answer comes up too.

    So on my screen I am looking at this:

    Enter the number of years you have been playing: 10
    Enter in the kind of guitar you play: Sorry...you have to have been playing for 10 years.

    So you see something is wrong somewhere and I suspect it is in the nested ifs.
    Code:
    import java.util.Scanner;
    
    public class NestedIfStatement
    {
    	public static void main(String[] args)
    	{
    		int numberOfYearsPlaying = 10;
    		String guitarPrerequisite = "Fender";
    		int userNumberOfYearsPlayed;
    		String userGuitarPlayed;
    		
    		Scanner keyboard = new Scanner(System.in);
    		
    		try{
    		
    		System.out.print("Enter the number of years you've been playing: ");
    		userNumberOfYearsPlayed = keyboard.nextInt();
    		
    		System.out.print("Enter in the kind of guitar you play: ");
    		userGuitarPlayed = keyboard.nextLine();
    		}
    		finally
    		{
    			keyboard.close();
    		}
    		
    		if(userNumberOfYearsPlayed >= numberOfYearsPlaying)
    		{
    			if(userGuitarPlayed == guitarPrerequisite)
    			{
    				System.out.println("Great! You are hired!");
    			}
    			else
    			{
    				System.out.println("Sorry...you have to have been playing for 10 years");
    			}
    		}
    	}
    }
    Last edited by 2kaud; May 25th, 2023 at 10:24 AM. Reason: Correct code tags

  2. #2
    Join Date
    Mar 2005
    Posts
    37

    Re: I don't know what is wrong with my program

    I could not see any thing that says how to post code. I suspected it would be [code] [/] but it looks like that didn't work. I'm using Java 20 its I think the latest version with Eclipse.

  3. #3
    Join Date
    Nov 2018
    Posts
    120

    Re: I don't know what is wrong with my program

    It's [code]
    Code:
    code goes here
    [/code]

    > userNumberOfYearsPlayed = keyboard.nextInt();
    This reads a number, but does NOT consume the newline at the end of it.

    > userGuitarPlayed = keyboard.nextLine();
    This expects a newline, and the newline at the end of "10\n" will do just fine.

    You need to remove the trailing newline of "10\n" somehow.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured