Incompatible operand types String and int - java

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

Related

Java number guessing

a. declare a final int, and assign a value of 6 as the guessed number
// b. create a Scanner to get user input
// c. use a do {} while loop to prompt the user to enter an integer between 1 and 10,
// assign the user input to an int, and compare to the guessing number
do{
} while ();
// d. if the number matches the guessed number,
// print out a message that the number entered is correct.
I am stuck on the do while loop portion of the problem
import java.util.Scanner;
public class Number {
public static void main(String[] args) {
int value = 6;
int guess = 0;
int num = 0;
do {
System.out.println("Please enter a number between 1 and 10: ");
Scanner number = new Scanner(System.in);
guess = number.nextInt();
} while (num <= 10);
if (guess == value);
System.out.println("Congratulations you guessed the correct number!");
if (guess != value);
System.out.println("The number does not match.");
}
}
This is the result I am getting. I cannot figure out why it wont print the messages saying the number is correct or the number did not match.
Please enter a number between 1 and 10:
4
Please enter a number between 1 and 10:
5
Please enter a number between 1 and 10:
6
The semicolon after the if statement stops it from working and makes no sense
if (guess == value);
^ No no no
Should be
if (guess == value) {
System.out.println("Congratulations you guessed the correct number!");
}
Or
if (guess == value)
System.out.println("Congratulations you guessed the correct number!");
You should also increment num or the while makes no sense
Remove the Semicolon after the ifstatement, and i strongly advise you to use {} to wrap all your statements.
Morover you should increase num inside your while loop, and move the guessing part inside your while loop. so the correct messages are printed out in every loop.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int value = 6;
int guess = 0;
int num = 0;
do {
System.out.println("Please enter a number between 1 and 10: ");
Scanner number = new Scanner(System.in);
guess = number.nextInt();
num++;
if (guess == value) {
System.out.println("Congratulations you guessed the correct number!");
break;
}
if (guess != value) {
System.out.println("The number does not match.");
}
} while (num <= 10);
}
}
You code basically looks like this:
ask user for a number from 1 to 10
and do this forever
now check whether the number entered is the right guess
So as long as the user does what he is told, you keep asking and reasking. You never get to "now check...".
The loop needs to encompass the checking for the right guess, and needs to be terminated on the right guess.
(Edited) I slightly misread the original code, thinking that 'num' was the input value. Nope, the input number is called 'number'. I suggest the counter be renamed for clarity, maybe 'guessCount'. And of course remember to increment it with each guess.

What possible exceptions are there if User enters String instead of Int?

I am just playing with Java.I'm trying to force my program to only accept number digits 1 and 2. I believe I have successfully done this using a while loop (please correct me if I'm wrong). But how do I go about printing an error statement if the user enters a string. eg: "abc".
My code:
while (response != 1 && response != 2) {
System.out.println("Please enter 1 for Car or 2 for Van: ");
response = scan.nextInt();
}
if (response == 1) {
vehicleType = VehicleType.CAR;
while (numPassengerSeats < 4 || numPassengerSeats > 7) {
System.out.println("Please enter the number of Passengers: ");
numPassengerSeats = scan.nextInt();
}
} else {
vehicleType = VehicleType.VAN;
while (true) {
System.out.println("Please enter the last maintenance date (dd/mm/yyyy): ");
String formattedDate = scan.next();
lastMaintenanceDate = formatDate(formattedDate);
if (lastMaintenanceDate != null)
break;
}
}
Let's have a look at javadoc for nextInt():
Scans the next token of the input as an int. An invocation of this
method of the form nextInt() behaves in exactly the same way as the
invocation nextInt(radix), where radix is the default radix of this
scanner.
Returns: the int scanned from the input
Throws:
InputMismatchException
- if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed
As per javadoc, it throws InputMismatchException if the user enters a String instead of an int. So, we need to handle it.
I think you have not successfully force your program to accept just integers since by using java.util.Scanner.nextInt(), user can still be able to input non integers, however java.util.Scanner.nextInt() will just throw an exception. Refer to this for possible exception thrown.
I have made a solution to force your program to accept just integers. Just follow the sample code below:
Sample code:
package main;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int response = 0;
Scanner scan = new Scanner(System.in);
while (response != 1 && response != 2) {
System.out.println("Please enter 1 for Car or 2 for Van: ");
try {
response = Integer.parseInt(scan.nextLine());
if (response != 1 && response != 2) {
System.out.println("Input is not in choices!");
}
} catch (NumberFormatException e) {
System.out.println("Input is invalid!");
}
}
scan.close();
}
}

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

How do I validate the less then zero inputs efficiantly without so many of the same else statements?

I am trying to create a computer simulation of money losses over blackjack games. However I am running into a bug where if I put a less then zero value in one of the prompts, the program has to go through all the other prompts before warning about the less then zero.
Is there a way to immediately warn about less then zero values without having to put the same exact else statement for each if over and over again?
private void menu()
{
boolean NonNumeric=false;
//This is so a different exception is thrown for the minimum stakes since it's a float.
boolean isDecimal=false;
while(getRounds()<=0 || getPlayers()<=0 || getStakes()<=0 )
{
try
{
Scanner input = new Scanner(System.in);
if(getRounds()<=0)
{
System.out.println("Enter number of rounds.");
setRounds(input.nextInt());
}
if(getPlayers()<=0)
{
System.out.println("Enter number of players.");
setPlayers(input.nextInt());
}
if(getStakes()<=0)
{
System.out.println("Enter minimum stakes.(Note: All players bet minimum only)");
isDecimal=true;
setStakes(input.nextFloat());
}
}
catch (InputMismatchException e ) //In case some idiot enters a letter or symbol.
{
//This if statement is so that a different message comes if the invalid entry is a float.
if(isDecimal==true)
{
System.out.println("Entry must be a number. Not a letter or symbol. Try Again.\n");
}
else
{
System.out.println("Entry must be a whole number. Not a letter, decimal, or symbol. Try Again.\n");
}
/*This boolean is so that the below if statement does not run if the user enters a letter
since the integer defaults back to a 0 on exception.*/
NonNumeric = true;
}
if(getRounds()<=0 || getPlayers()<=0 || getStakes()<=0)
{
System.out.println("Number must be greater than 0.\n");
}
}
}
Modularize. Create a method (or even a class) that takes an input and accepts it only if it meets conditions. For example
private int myIntGetter(String caption, boolean forcePositive) {
System.out.println(caption);
Scanner input = new Scanner(System.in);
int intValue = input.nextInt();
while ((forcePositive) && (intValue <=0)) {
System.out.println("Number must be greater than \0");
System.out.println(caption);
intValue = input.nextInt();
}
// here intValue is valid
return intValue;
}
If you're not to concerned with being nice to your user:
do{
System.out.println("Enter number of rounds. Rounds must greater than zero.");
setRounds(input.nextInt());
}while( getRounds()<=0);
You can do that for each thing the user has to enter. It's quick and dirty.

Categories