Jump to content

[SOLVED] Java Question (If/Else)


Recommended Posts

I'm working on a program for a class where you input a string, then choose an option to do things to it. I've got the input boxes and stuff, and can collect the information and spit it back out, but for some reason my if statements aren't working. It goes straight to else even though I output my selection so I know that's right. Here's the code- any help would save me hours.

 

import javax.swing.JOptionPane;

public class StringProcessor {
public static void main(String[] args) {

//Prompt user to enter a string
String input = JOptionPane.showInputDialog(null,
		"Enter initial string:",
		"Initial Input", JOptionPane.QUESTION_MESSAGE);

//Show selection
JOptionPane.showMessageDialog(null, "You entered: " + input);

//Declare and initialize output string
String output = "";

//Prompt user to select a choice
String option = JOptionPane.showInputDialog(null,
		"V (count the number of vowels in a string)\n" +
		"R (display the string in reverse)\n"          +
		"S (change the current string)\n"              +
		"D (display the current string)\n"             +
		"Q (quit)\n\n",
		"Menu Choice", JOptionPane.QUESTION_MESSAGE);

//Show selection
JOptionPane.showMessageDialog(null, "You entered: " + option);


		if (option == "v" || option == "V") {
			//Count the vowels in a string			
		}
		else if (option == "r" || option == "R") {
			//Display the string in reverse
		}
		else if (option == "s" || option == "S") {
			//Change the current string
			input = JOptionPane.showInputDialog(null,
				"Enter initial string:",
				"Initial Input", JOptionPane.QUESTION_MESSAGE);
		}
		else if (option == "d" || option == "D") {
			//Display the current string
			JOptionPane.showMessageDialog(null, input);
		}
		else if (option == "q" || option == "Q") {
			//Quit
			System.exit(0);
		}
		else {
			//What?
			JOptionPane.showMessageDialog(null, "What..?");
			System.exit(0);
		}

}
}

Link to comment
https://forums.phpfreaks.com/topic/109719-solved-java-question-ifelse/
Share on other sites

The problem there is that the compiler isn't doing what you think it's doing. You have to use the variable.equals("whatever") to compare those strings.

 

In your case, something like:

 

else if ( option.equals( "q" ) || option.equals( "Q" ) ) {
   System.exit(0);
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.