Java code not running as planned - java

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

Related

Having trouble with implementing a system that detects if an input is a integer or not

I'm trying to make a system that asks the user how many times they want a phrase to be repeated and then it checks if the answer is an integer or a string. The program works well when I don't try to implement this system and leave it just at asking the phrase and how many times it should be repeated but it falls appart when I try to check if the amount of times is an integer or not.
import java.util.*;
public class Phrase {
public static Scanner phraseScan = new Scanner (System.in);
public static Scanner amountScan = new Scanner (System.in);
public static void main (String[] args ) {
System.out.println("What phrase do you want repeated?");
String phrase = phraseScan.nextLine();
int phraseLoops = 0;
System.out.println("How many " + phrase + "s" + " do you want?");
int desiredPhraseLoops = amountScan.nextInt();
for (;;) {
if (!amountScan.hasNextInt()) {
System.out.println("Integers only please");
amountScan.next();
}
desiredPhraseLoops = amountScan.nextInt();
if (desiredPhraseLoops >= 0) {
System.out.println("Valid amount!");
continue;
} else {
break;
}
}
System.out.println(desiredPhraseLoops + " " + phrase + "s coming your way!");
do {
System.out.println(phrase);
phraseLoops++;
} while (phraseLoops != desiredPhraseLoops);
System.out.println("You printed " + phraseLoops + " " + phrase + "s" );
}
}
What I've tried:
try {
desiredPhraseLoops = amountScan.nextInt();
} catch (InputMismatchException exception) {
System.out.println("This is not an integer.");
}
if (!amountScan.hasNextInt()) {
System.out.println("Good.");
} else {
System.out.println("Enter an Integer please.");
}
Any time I tried anything, it would ask which phrase I wanted and how many times I wanted it repeated. And then the program just stopped afterward, no matter if I put in an integer or a string, it just didnt give me any other prompts.
The output is this:
What phrase do you want repeated?
Test
How many Tests do you want?
3
And that's it.
To begin with, just use one Scanner object. You don't need more than that for keyboard input.
If you like, you can just stick with the Scanner#nextLine() method, for example:
Scanner userInput = new Scanner(System.in);
String phrase = "";
while (phrase.equals("")) {
System.out.println("What phrase do you want repeated?");
phrase = userInput.nextLine();
// VALIDATION:
// Was anything other than a empty string (spaces)
// or longer than 2 characters supplied?
if (phrase.trim().equals("") || phrase.length() < 3) {
// Nope!
System.err.println("Invalid Input!. Enter a proper phrase!");
phrase = "";
}
// Yes, allow the prompt loop to exit.
}
String phraseLoopsNumber = "";
while (phraseLoopsNumber.equals("")) {
System.out.println("How many " + phrase + "s" + " do you want?");
phraseLoopsNumber = userInput.nextLine();
// VALIDATION:
// Did the User supply a string representation of an integer value?
if (!phraseLoopsNumber.matches("\\d+")) {
// Nope!
System.out.println("Invalid Input (" + phraseLoopsNumber + ")! An integer value is expected!");
phraseLoopsNumber = "";
}
// Yes he/she/it did...Allow prompt loop to exit.
}
int numberOfLoops = Integer.parseInt(phraseLoopsNumber);
// Do what you have to do with the desired number of loops contained
// within the numberOfLoops integer variable.
In the above code, the String#matches() method was used along with a small Regular Expression (RegEx). The "\\d" expression passed to the matches() method checks to see if the string it is working against contains all (1 or more) digits.
If however you're hell bent on using the Scanner#nextInt() method then you can do it this way:
int numberOfLoops = -1;
while (numberOfLoops == -1) {
System.out.println("How many " + phrase + "'s" + " do you want?");
// Trap any input errors against the Scanner.nextInt() method...
// This would be a form of validation.
try {
numberOfLoops = userInput.nextInt();
// Consume the newline from ENTER key in case a nextLine() prompt is next.
userInput.nextLine();
} catch (Exception ex) {
System.out.println("Invalid Input! An integer value is expected!");
// Consume the newline from ENTER key in case a nextLine() prompt is next.
// The first one above would of been skipped past if nextInt() threw an exception.
userInput.nextLine();
numberOfLoops = -1;
continue; // continue loop so as to re-prompt
}
// Further Validation:
// Did the User supply a number greater than 0?
if (numberOfLoops < 1 ) {
// Nope!
System.out.println("Invalid Input (" + numberOfLoops + ")! A value 1 or greater is expected!");
numberOfLoops = -1;
}
// Yes he/she did...Allow prompt loop to exit.
}
// Do what you have to do with the desired number of loops contained
// within the numberOfLoops integer variable.

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

How to keep the program running if the user entered Y?

Here is my code:
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner Keyboard = new Scanner(System.in);
{
System.out.println("What is the answer to the following problem?");
Generator randomNum = new Generator();
int first = randomNum.num1();
int second = randomNum.num2();
int result = first + second;
System.out.println(first + " + " + second + " =");
int total = Keyboard.nextInt();
if (result != total) {
System.out.println("Sorry, wrong answer. The correct answer is " + result);
System.out.print("DO you to continue y/n: ");
} else {
System.out.println("That is correct!");
System.out.print("DO you to continue y/n: ");
}
}
}
}
I'm trying to keep the program to continue but if the user enters y and closes if he enters n.
I know that I should use a while loop but don't know where should I start the loop.
You can use a loop for example :
Scanner scan = new Scanner(System.in);
String condition;
do {
//...Your code
condition = scan.nextLine();
} while (condition.equalsIgnoreCase("Y"));
That is a good attempt. Just add a simple while loop and facilitate user input after you ask if they want to continue or not:
import java.util.*;
class Main
{
public static void main(String [] args)
{
//The boolean variable will store if program needs to continue.
boolean cont = true;
Scanner Keyboard = new Scanner(System.in);
// The while loop will keep the program running unless the boolean
// variable is changed to false.
while (cont) {
//Code
if (result != total) {
System.out.println("Sorry, wrong answer. The correct answer is " + result);
System.out.print("DO you to continue y/n: ");
// This gets the user input after the question posed above.
String choice = Keyboard.next();
// This sets the boolean variable to false so that program
// ends
if(choice.equalsIgnoreCase("n")){
cont = false;
}
} else {
System.out.println("That is correct!");
System.out.print("DO you to continue y/n: ");
// This gets the user input after the question posed above.
String choice = Keyboard.next();
// This sets the boolean variable to false so that program
// ends
if(choice.equalsIgnoreCase("n")){
cont = false;
}
}
}
}
}
You may also read up on other kinds to loop and try implementing this code in other ways: Control Flow Statements.

JOptionPane, help on return

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

Is there a way to make an "if" inside another if"

How do I make it so that if the username is incorrect, it doesn't ask for the password but immediately says that the username is incorrect?
import java.util.Scanner;
public class SecurityPasscode
{
public static void main(String[] args)
{
Scanner user_input = new Scanner(System. in );
System.out.println("Enter Username");
String username;
username = user_input.next();
if (username.equals("username"))
System.out.println("Enter Password");
String password;
password = user_input.next();
if (password.equals("password"))
System.out.println("Welcome back " + username + "!");
if (!"password".equals(password))
System.out.println("That password is incorrect.");
else if (!"username".equals(username))
System.out.println("That username is incorrect.");
}
}
Add { after your first if....
Note that these two blocks of code are not the same:
if(something1)
command1;
command2;
if(something2)
command3;
else if(something3)
if(something1) {
command1;
command2;
if(something2)
command3;
}
else if(something3)
In the first code, the else corresponds to the last if. In the second code, it corresponds to the first if. Furthermore, in the first code, command2 is not in the scope of the external if because Java doesn't really cares about indentation..
if (username.equals("username")){
System.out.println("Enter Password");
}else{
String password;
password = user_input.next();
if (password.equals("password")){
System.out.println("Welcome back " + username + "!");
}else{
System.out.println("That password is incorrect.");
}
}
if (condition)
{
if (another condition)
{
// statements here
}
}
yes...
if(eval)
if(anotherEval)
....
code
you could have any number of nested if as you like :)

Categories