JOtionpane and control structure - java

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

Related

How can I add an error if the input doesn't match with it's variable

I just got into java programming today and I made a calculator that I'm so proud of as a first project even though I took many parts of it from the internet like the Scanner code and how to allow input for the user, but I don't know how to print out an error if the input doesn't match the variable assigned to, ex: user inputs a string instead of an integer,
You could use a try and catch statement to determine if the input you need is of the type that you want.
try {
// Block of code to try
}
catch(Exception e) {
// error if it's not the type you are looking for
}
As the answer above states you can use try and and catch and also create a custom exception but that won't really help you because just copying it won't make you understand it and there is a lot of concepts you should learn before you take a look at that.
If you want to learn how to code/learn java I can recommend you this video series by BroCode https://www.youtube.com/watch?v=NBIUbTddde4&list=PLZPZq0r_RZOMhCAyywfnYLlrjiVOkdAI1
It's really good for beginners and easy to follow along

How to check if the input given by the user is Y or N

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");
}

If statement not comparing JInputDialog value

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...

Source of Infinite Loop

Everytime I run this code, the console goes into an infinite loop printing "Please input a number". I do not understand why this is happening. Thanks in advance.
boolean check = true;
int temp = 0;
while(check==true){
try{
temp= asker.nextInt();
check = false;
}
catch(InputMismatchException e){
System.out.println("Please input a number.");
}
}
Edit: asker is a Scanner. The purpose of the code is to loop until an integer is inputted by the user.
The method asker.NextInt() is throwing an InputMismatchException, indicating that the input received from asker (assuming it's a Scanner) isn't actually an integer. This exception causes the loop to restart without setting check to false.
Print the exception within the catch block to get more information about the failure. But most likely, you're feeding your application something (lots and lots of something, if it's looping like that) that doesn't actually contain integer values.
You never want to actually "Use" try/catch--by that I mean don't use it as part of your program logic--this is what you are doing.
One big problem is that, like your app, you don't see the stack trace. Eating a stack trace in an exception is almost always wrong.
If you do have to catch an exception, handle it near the catch as well as you can, but it's better to set up your code so that the exception can't be thrown anyway.
Discard this advice if your teacher told you to do it this way, but remember in the back of your mind that it's poor form.
Also don't tell your teacher that it's poor form :) he either doesn't know in which case he won't understand why or he does know and is using this to show you how try/catch works.
What is asker, a Scanner? If nextInt() fails, it doesn't consume any input, so when you catch your exception and loop back around to try again, it ends up just reading the same bad input again.
You should do something in the catch block to consume the invalid input, so that the next time around, it can read some different input. Call asker.nextLine() maybe, and ignore the return value.
You need to break the loop and report why the loop occurs
boolean NotValid = true;
int temp = 0;
while(NotValid){
try{
temp= asker.nextInt();
NotValid = false;
break; // stop
}
catch(InputMismatchException e){
System.out.println("Please input a number. reason why:");
System.out.println(e);
NotValid = true;
}
}

User input validation for JOptionPane.showInputDialog

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.

Categories

Resources