I'm just learning JAVA and having a bit of trouble with this particular part of my code. I searched several sites and have tried many different methods but can't seem to figure out how to implement one that works for the different possibilities.
int playerChoice = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter number for corresponding selection:\n"
+ " (1) - ROCK\n (2) - PAPER\n (3) - SCISSORS\n")) - 1;
I imagine I need to have some type of validation even for when the user has no input as well as an input that is not 1, 2 or 3. Anyone have suggestions on how I can accomplish this?
I tried a while loop, an if statement to check for null before converting the input to an integer, as well as a few different types of if else if methods.
Thanks in advance!
You need to do something like this to handle bad input:
boolean inputAccepted = false;
while(!inputAccepted) {
try {
int playerChoice = Integer.parseInt(JOption....
// do some other validation checks
if (playerChoice < 1 || playerChoice > 3) {
// tell user still a bad number
} else {
// hooray - a good value
inputAccepted = true;
}
} catch(NumberFormatException e) {
// input is bad. Good idea to popup
// a dialog here (or some other communication)
// saying what you expect the
// user to enter.
}
... do stuff with good input value
}
Read the section from the Swing tutorial on How to Make Dialogs, which actually shows you how to use JOptionPane easily so you don't need to validate the input.
There are different approaches your could use. You could use a combo box to display the choices or maybe multiple buttons to select a choice.
The tutorial also shows you how to "Stopping Automatic Dialog Closing" so you can validate the users input.
Related
my code
I'm pretty much brand new to java and coding been practicing for a couple weeks now and I'm trying to figure out how to get my output to only display the else statement when NONE of the 2 'if' options have been inputted.
for ex. i have 2 categories of food places, Mexican and American. When the user is prompted to enter a category it displays the array of restaurants just fine but I cant get the else statement to not pop up with the first if option. No matter what if the first 'if' option is inputted the else statement gets printed, how do i stop that and only have it print when 'American' or 'Mexican' isn't inputted.
This "else" referrers to second "if". Use "switch-case" construction instead with "else" value as default.
You should use an if-elseif-else block instead of if ... if-else. That's the issue.
if (/* code for mexican */) {
System.out.println("mexican options...");
} else if (/* code for american */) {
System.out.println("american options...");
} else {
System.out.println("Sorry, no options available");
}
to summarise it give me any idea or solution on how I could fix it.
I tried what is given in the code below.
System.out.print("Want to continue Shopping or end your shopping spree and want the bill for your shopping (answer in Y or N)");
String end = sc.next();
if(end =="Y")
System.out.println("hello");
I expect the output hello in the above code, but the actual results are nothing the program just ends.
First of all, I have no idea what your question is about exactly. I can't see any information on which programming language you are using (I suppose Java) or on which operating system you are working.
But I've got an idea what the problem might be: As you are using stdout, I suppose the program happens on a Console or Terminal. And in some environments, the cmd window will close after there program terminated (when working with an IDE like VS Community, which I don't know if you do or not, given no context). If this is the case, "hello" will be printed but you won't see it because the window closes immediately. Try to add some kind of getline at the end and try again.
Supposing sc is a Scanner object.
String comparison must be done with the equal method instead of using == because by doing that you'll compare the object's referer in the memory instead of the String content, try this:
System.out.print("Want to continue Shopping or end your shopping spree and want the bill for your shopping (answer in Y or N)");
String end = sc.next();
if(end.equals("Y")) {
System.out.println("hello");
}
please help me, i know its too easy but i cant answer it, waaah, i think i have an headache now, the problem was:
Prompt the user for a message and ask how many times to print it.
your program output should be as follows:
How will you like me to print?
How many times do you want me to print it?
and my prof told us that we should use JOptionPane and control structure for the two question, and the answer should be in System.out.println..
please help me, thank you,
Start by taking a look at How to Make Dialogs.
You will want to use JOptionPane#showInputDialog to get the information from the user, you will need to do this (at least) twice, once to get the message and once to the count.
You could use a do-while to ensure that the user enters a valid, numerical value...
int count = 0;
do {
String input = JOptionPane.showInputDialog(...);
try {
count = Integer.parseInt(input);
} catch (NumberFormatException exp) {
// You could show a JOptionPane.showMessageDialog here as an error message
}
} while (count != 0);
Once you have all the information, you will could use a for-loop to print the result...
Take a look at:
JOptionPane Java Docs
The for Statement
For more details
So I have an If Statement. It's set to compare a value taken fron user input using JOptionPane.showInputDialog. But if the values are the same, it doesn't do anything...
Example: The user has to enter the value 4. When the Input Dialog appears, the user types 4.
Then, it's supposed to win, because if userInput = 4 {win}. But even if the userInput is 4, nothing will happen...
I thik I'm not explaining very well...
EDIT: Ok, I found the problem... I'm stupid... The problem was I declared another int for the num inside the method, so it wasn't reachable outside the method...
It's important to remember that the input dialog takes strings so the number that you enter will actually be stored in memory as a String object.
int intInput = Integer.parseInt(stringInput);
That will parse the user's input and store as an integer. It's probably best to check that it's possible to parse the input before actually parsing so that the program doesn't crash/bug out.
EDIT: You could also do this:
if(userInput.equals("4")) {
JOptionPane.showMessageDialog(null, "win");
}
Ok, I found the problem... I'm stupid... The problem was I declared another int for the num inside the method, so it wasn't reachable outside the method...
So i've always been having problems with .toLowerCase and I've checked loads of articles, Videos and books on how it works. I tried making a silly game as a joke for my friends and obviously this wont work
What's the best way to fix it and how do i .toLowerCase() work? If a simple explanation could be given i'd be very happy!!
:)
the "Choice " is a static String.
public static void part1()
{
System.out.println("Welcome to Chapter ONE ");
System.out.println("This is just a simple Left Right options.");
System.out.println("-------------------------");
System.out.println("You emerge into a cave like structure, It's seems very weird and creeps you out a little, Yet, You continue on your journey \n You see a that you have reached a 'Dead End' and \n now you have two choices: Either go Left into the weird corner, Or Go Right.. Into the Well-Lit Area.");
choice = input.next();
if(choice.toLowerCase()=="left")
{
deathPre();
}
else if(choice.toLowerCase()=="right")
{
TrFight();
}
}
So this is the part where it doesnt work (Yeah, It's the first part ironically)i've tried other ways to make this work. Though this being the simplest for me to do suddenly became impossible.
Please help!
Logic : If the user inputs "Left" (doesnt matter which case because i convert it to lower case either way).. It should send the user to "deathPre();
And if he inputs "right" it should go to "TrFight();
Anything else causes an error which i dont mind. But i need the "Left" and "Right" to work
Make sure you compare strings with .equals() you could also use
.equalsIgnoreCase("left")
If you use the second one you don't need to use '.toLowerCase()'
Edit:
Like Erik said you could also use
.trim().equalsIgnoreCase("left")
Like Zim-Zam already commented, you need to compare the strings using equals, not the == operator:
if(choice.toLowerCase().equals("right"))
...
else if(choice.toLowerCase().equals("left"))
.toLowerCase() is probably doing its job just fine.
You need to try this instead:
public static void part1()
{
System.out.println("Welcome to Chapter ONE ");
System.out.println("This is just a simple Left Right options.");
System.out.println("-------------------------");
System.out.println("You emerge into a cave like structure, It's seems very weird and creeps you out a little, Yet, You continue on your journey \n You see a that you have reached a 'Dead End' and \n now you have two choices: Either go Left into the weird corner, Or Go Right.. Into the Well-Lit Area.");
choice = input.next();
if(choice.toLowerCase().equals("left"))
{
deathPre();
}
else if(choice.toLowerCase().equals("right"))
{
TrFight();
}
To compare two strings, use the equals method in String object.