JOptionPane, help on return - java

this is my first post on this website, as this website has been a lot of help. I have came up with not so much a problem, but something I want to learn on how to do. Here is my code
String a = JOptionPane.showInputDialog(null,"Please pick something for me to do master:\nMynumber,Read2me, Conversions");
if (a.equals("Mynumber"))
{
MyNumber = Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter your number: "));
String b = JOptionPane.showInputDialog(null,"Was Your number "+MyNumber+"\n Y/N");
if (b.equals("y"))
{
JOptionPane.showMessageDialog(null,"Good...good, now lets play with\n your number");
}
else if(b.equals("N"))
{
JOptionPane.showMessageDialog(null,"returning");
My goal is to when it gets to the last on (when the user types n) I want it to return to the starting String, or String A, how would I implement this into my code

Add a loop to your code, for example
while(true) { // instead of while(true) you can also write other condition
String a = JOptionPane.showInputDialog(null,"Please pick something for me to do master:\nMynumber,Read2me, Conversions");
if (a.equals("Mynumber")) {
MyNumber = Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter your number: "));
String b = JOptionPane.showInputDialog(null,"Was Your number "+MyNumber+"\n Y/N");
if (b.equals("y")) {
JOptionPane.showMessageDialog(null,"Good...good, now lets play with\n your number");
}
else if(b.equals("N")) {
JOptionPane.showMessageDialog(null,"returning");
}
}
}

Related

How can I validate user input in Java

I am currently experimenting with Java, trying to get the user to input an integer. If the user doesn't enter an integer I want a message to appear saying "You need to enter an Integer: " with a completely new input field to the original one.
Code:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner inputScanner = new Scanner(System.in);
int counter = 0;
boolean run = true;
int userInput = 0;
while (run) {
System.out.print("Enter an integer: ");
if (inputScanner.hasNextInt()) {
userInput = inputScanner.nextInt();
} else if (!inputScanner.hasNextInt()) {
while (!inputScanner.hasNextInt()) {
System.out.print("You need to enter an Integer: ");
userInput = inputScanner.nextInt();
}
}
System.out.println(userInput);
if (counter == 6) {
run = false;
}
counter++;
}
}
}
At the moment the code above gives an Exception error ("java.util.InputMismatchException"). I have tried to use a try/catch but this doesn't really work because I want the user to see the second message ("You need to enter an Integer") everytime they don't enter an integer and I don't want it to re-loop around the main run loop for the same reason. I'm sure there is a better way to do this, however I am not sure of it. Any help will be massively appreciated, thanks in advance.
In this case it would make more sense for the Scanner to use hasNextLine and then convert the String to an Integer. If that you could do something like this:
try {
new Integer(inputScanner.hasNextLine);
} catch (Exception e) {
System.out.println(“<error message>”)
}
In place of the if(inputScanner.hasNextInt()) due to the fact that the hasNextInt function will error out if there is not an Integer to be read.

Incompatible operand types String and int

Just a code of a bank with few functions, I am only trying to learn the way if loops are made. Seem to be getting "Incompatible operand types String and int" error on all lines that have an if,else if.
import java.util.Scanner;
public class Bank
{
//create variables
int pac;
int confirm;
int pin;
int Bal_or_Exit;
public static void main(String args[])
{
//Receive any PAC and create if loop for continue or exit
Scanner in = new Scanner(System.in);
System.out.println("Please Enter your Personal Access Code (P.A.C)");
String pac = in.nextLine();
System.out.println(pac + " is the P.A.C you have just entered.");
System.out.println("Press 1 to continue, Press 2 to cancel");
String confirm = in.nextLine();
if(confirm == 1)
//if loop created for confirm or exit...create another if loop for a pin of 0207
{
System.out.println("Please Enter your Pin");
String pin = in.nextLine();
if(pin == 0207)
//if loop created for pin, only access if pin=0207..access granted and
option of viewing Account Balance or Exit
{
System.out.println("Welcome!");
System.out.println("Press 1 for Balance");
System.out.println("Press 2 to Exit");
String Bal_or_Exit = in.nextLine();
//if 1 is pressed, display balance of €2965.33
if(Bal_or_Exit == 1)
{
System.out.println("Your balance is €2965.33");
}
//if 2 is pressed, display goodbye message
else if(Bal_or_Exit == 2)
{
System.out.println("GoodBye, Have a Nice a Day!");
}
//if anything else is pressed display error message
else
{
System.out.println("We're Sorry, An Error has Occured");
}
}
//if pin is anything except 0207 , display wrong pin message
else
{
System.out.println("The PIN you Have entered is incorrect");
}
}
//if confirm = 2 (exit), display exit and goodbye message
else if(confirm == 2)
{
System.out.println("You have selected exit");
System.out.println("Have a Nice Day!");
}
//if confirm is not = 1 or 2, display error message
else
{
System.out.println("We're Sorry, An Error has Occured");
}
}
}
You have that error due to Scanner#nextLine() returns a String, so, when you call:
String confirm = in.nextLine();
confirm is a String and then you're trying to compare:
if(confirm == 1)
In other words:
if (String == int)
You should either:
Call Scanner#nextInt()
Change your if as follows:
if (confirm.equals("1"))
There are multiple problems with your code. Take if(pin == 0207) as an example:
pin is a string so it can't be compared to a number like that
strings need to be compared via equals() and not ==
0207 is an octal literal, i.e. in decimal it would be the number 135.
To fix that change pin == 0207 to pin.equals( "0207" ) and the other string comparisons such as confirm == 1 accordingly too.
You could also try to parse the strings to numbers, e.g. Integer.parseInt( confirm) == 1 but since 0207 is probably meant to be used as it is you need to use String here anyways.
You can't compare a string with an integer because they are two different data types. You will have to cast the string to an integer to do this.
Like this:
if(Integer.parseInt( confirm ) == 1)
Alternatively you can cast the user input before storing it in the string variable.
int confirm = Integer.parseInt(in.nextLine());
You can also read the user input as an integer instead of a string.
int confirm = in.nextInt();
For the value 0207 it would be more sensible to compare it as a string because of the leading 0. This information would get lost if you compare it as an integer. To compare strings you can use the equals() method.
if(pin.equals("0207"))

Java code not running as planned

This isn't the entire code, just the problem area. (Full code below)
if (passLength > 4) {
System.out.println("Signup alost complete.");
Random rand = new Random();
int randm = rand.nextInt(100000) + 1;
System.out.println(
"To confirm you are not a robot, please enter this code: "
+ randm);
String code = userInput.next();
if (code.equals(randm)) {
System.out.println("Thank you, " + userName);
System.out.println(
"You may now login. Begin by entering your username");
if (userInput.equals(userName)) {
System.out.println("Now please enter you password");
}
// Where the rest of the program will go
}
else {
System.out.println("The code entered is incorrect.");
}
}
else {
System.out.println("Invalid Password");
}
I am making a program where the user makes an account, then later signs in. The part I am having trouble with is a verification to ensure the user is human (they obviously are, but still). After creating their username and password, I generate and print a random int, and they have to type it back.
My problem is that the program always skips to the else statement, and prints "The code entered is incorrect." Even when I enter it perfectly.
Can anyone tell me what I'm doing wrong?
Below is the entire code, just in case.
public static void main(String[] args) {
System.out.println("Hi! To begin please choose your username.");
System.out.println("To do this, please enter your username below. ");
System.out.println("This name must be at least three characters.");
Scanner userInput = new Scanner(System.in);
String userName = userInput.next();
int nameLength = userName.length();
if (nameLength > 2) {
System.out.println("Now please enter your password.");
System.out
.println("This password must be at lease five characters");
String passWord = userInput.next();
int passLength = passWord.length();
if (passLength > 4) {
System.out.println("Signup alost complete.");
Random rand = new Random();
int randm = rand.nextInt(100000) + 1;
System.out.println(
"To confirm you are not a robot, please enter this code: "
+ randm);
String code = userInput.next();
if (code.equals(randm)) {
System.out.println("Thank you, " + userName);
System.out.println(
"You may now login. Begin by entering your username");
if (userInput.equals(userName)) {
System.out.println("Now please enter you password");
}
// Where the rest of the program will go
}
else {
System.out.println("The code entered is incorrect.");
}
}
else {
System.out.println("Invalid Password");
}
}
else {
System.out.println("Invalid Username");
}
}
You are comparing a String with an integer, which can't be the same obviously.
int randm = rand.nextInt(100000) + 1;
...
String code = userInput.next();
if (code.equals(randm))
To solve the problem you could convert the integer to a String and compare the strings (or the other way).
String randm = String.valueOfrand.nextInt(100000) + 1;
...
String code = userInput.next();
if (code.equals(randm)) // Comparing string now
Edit : As #Pshemo pointed out, int code = userInput.nextInt(); will do the work given that you compare the integers with ==.
It's because randm is int and code is String. So the code if (code.equals(randm)) always results to false.
You cannot compare a string and an integer.
Trying taking the input as an integer instead of a String.
String code = userInput.next();
Instead use:
int code= userInput.nextInt();
if(code==randm)
Or you could convert the integer to a String as well

Asking the user if they want to give multiple inputs

Im working on an assignment for an intro to java class and having some difficulty accounting for a situation when a user needs to give multiple inputs. The problem is given as follows:
"Ask the user to input a number. You should use an input dialog box for this input. Be sure to convert the String from the dialog box into a real number. The program needs to keep track of the smallest number the user entered as well as the largest number entered. Ask the user if they want to enter another number. If yes, repeat the process. If no, output the smallest and largest number that the user entered.
This program outputs the largest and smallest number AT THE END of the program when the user wants to quit.
Also, your program should account for the case when the user only enters one number. In that case, the smallest and largest number will be the same."
My issue is that I cannot figure out how to make the program continuously ask the user if they want to input another number....for as many times as they say yes (obviously). I know I will have to use a loop or something, but I am a beginner with this and do not know where to start. Any help would be appreciated, and thanks in advance!
Here is what I have so far:
package findingminandmax;
import javax.swing.JOptionPane;
public class Findingminandmax
{
public static void main(String[] args)
{
String a = JOptionPane.showInputDialog("Input a number:");
int i = Integer.parseInt(a);
String b = JOptionPane.showInputDialog("Would you like to input another number? yes or no");
if ("yes".equals(b)) {
String c = JOptionPane.showInputDialog("Input another number:");
int j = Integer.parseInt(c);
int k = max(i, j);
JOptionPane.showMessageDialog(null, "The maximum between " + i +
" and " + j + " is " + k);
} else {
JOptionPane.showMessageDialog(null, "The maximum number is " + i );
}
}
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
}
String b = JOptionPane.showInputDialog("Would you like to input another number? yes or no");
while(b.equalsIgnoreCase("yes")){
String c = JOptionPane.showInputDialog("Input another number:");
// your logic
b = JOptionPane.showInputDialog("Would you like to input another number? yes or no");
}
// then have your logic to print maximum and minimum number
But to get Yes/No inputs use a Confirm dialogbox rather than a input dialogbox
e.g.
int b = JOptionPane.showConfirmDialog(null, "Would you like to input another number? yes or no", "More Inputs", JOptionPane.YES_NO_OPTION);
while (b == JOptionPane.YES_OPTION) {
// your logic
}
while(true) {
//do stuff
if ("yes".equals(b)) {
//do other stuff
} else { break; }
}

App ignores input after the Scanner.nextLine() method

I'm new to java and I decided to write a simple program to practice IFs. Here's what it should do:
Ask the user about the currency.
Ask the user about the amount of money he wants to transfer.
Calculate the commission rate and show the details to the user.
Ask the user for confirmation; if he types "y" , the program should print "A". If he types "n" , the program should print "B".
Here's the code :
import java.util.Scanner;
public class CommissionRate {
static String Confirm;
static byte CommissionRate=10;
static String Commission="1%.";
static double TotalCost;
static double MoneyAmount;
static byte CurrencyNum;
static char CurrencySign;
static Scanner sc = new Scanner(System.in);
public static void Currency(){
System.out.println("Please choose your desired currnecy.");
System.out.println("1.USD");
System.out.println("2.EUR");
System.out.println("3.GBP");
System.out.println("4.CAD");
System.out.println("5.CNY");
System.out.println("6.JPY");
CurrencyNum = sc.nextByte();
if (CurrencyNum==1|CurrencyNum==4) {
CurrencySign= '$';
}
else {
if (CurrencyNum==2){
CurrencySign='€';
}
else {
if (CurrencyNum==3){
CurrencySign='£';
}
else {
if (CurrencyNum==5|CurrencyNum==6){
CurrencySign='¥';
}
}
}
}
}
public static void MoneyAmount() {
System.out.println("Please enter the amount of money you would like to transfer :");
MoneyAmount = sc.nextDouble();
if (MoneyAmount>499 & MoneyAmount<10000){
CommissionRate=5;
Commission="0.5%.";
}
else{
if (MoneyAmount>10000){
CommissionRate= 3;
Commission="0.3%.";
}
}
TotalCost = MoneyAmount + MoneyAmount * CommissionRate/1000;
System.out.println("Please confirm the transfer. ( y/n ) ");
System.out.println("A transfer of "+MoneyAmount+CurrencySign+".");
System.out.println("Commission rate is "+Commission);
System.out.println("You need to pay " + TotalCost+"." );
sc.nextLine();
Confirm = sc.nextLine();
if (Confirm=="y"){
System.out.println("A");
}
else if (Confirm=="n") {
System.out.println("B");
}
}
}
At first , the program wouldn't wait for the user to confirm/abort the transfer and it would print "B". Then , I read this and added the "sc.nextLine()". However the program just ignores the last if and doesn't print anything. Any ideas on what causes the problem and how to solve it ?
p.s.: Here's what I get when running the program:
Please choose your desired currnecy.
1.USD
2.EUR
3.GBP
4.CAD
5.CNY
6.JPY
2 // my input
Please enter the amount of money you would like to transfer :
120 // my input
Please confirm the transfer. ( y/n )
A transfer of 120.0€.
Commission rate is 1%.
You need to pay 121.2.
y // my input
please try
if (Confirm.equals("y")){
and
else if (Confirm.equals("n"))
with == you compare the object references not the values.
Try equals instead of == and one times should be sc.nextLine();
Confirm = sc.nextLine();
if (Confirm.equals("y")){
instead of
sc.nextLine();
Confirm = sc.nextLine();
if (Confirm=="y"){

Categories