Hello, I'm currently taking AP Computer Science with no prior experience with programming and I am facing a bit of a problem with the last problem on my programming assignment.

You see, what I have to do is write a program that displays a name four times either horizontally or vertically depending on whether a V or an H is inputted. In other words, if a V is typed in, the name would be displayed like this:

1. V) Bob
2. V) Bob
3. V) Bob
4. V) Bob

and if an H is typed in, the name would be displayed like this:

1. H) Bob 2. H) Bob 3. H) Bob 4. H) Bob

I also must use a while loop and I can ignore what would happen if a user were to input a Z, etc.

Unfortunately, I've run into a problem. No matter what I have tried, it only comes out with the same output (which is whatever I've put in the else part of the if-else statement).

Here is my code as of now:

Scanner input = new Scanner(System.in);
		System.out.print("Enter name: ");
		String name = input.nextLine();
		System.out.print("Enter a V or an H: ");
		String letter = input.nextLine();
		int k = 1;
		while (k != 5)
			if (letter == "V")
				System.out.println(k+ ". " + letter + ") " + name);
				System.out.print(k+ ". " + letter + ") " + name + " ");

Please keep in mind that all we've learned thus far (besides the different types of data types and such) is for, if, if-else, do...while, and while loops; print and println; the Scanner class; and how to do math with operators and the Math class.

Edited by akemi3: n/a

5 Years
Discussion Span
Last Post by akemi3

letter == "V" The == tests for letter and "V" both being exactly the same Object, which they are not, so it's always false.
To test whether two string Objects contain the same sequence of characters you need the equals method, as in letter.equals("V")

Edited by JamesCherrill: n/a


This fixed the problem! I have not been taught this method at all, so thank you very much! I appreciate it.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.