I have a problem with my java programs when I use if statements. In fact the programs don't run well and completely as I write. To tell you the truth I'm really confused about it because I don't know where is the problem from...
For example I've written these codes but when I run them, I can't get the city codes:
import java.util.Scanner;
public class Code {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Give the name, Get the code!\n* * * * * * * * * * * * * * *\n");
System.out.print("Please enter the name of the country : ");
String countryInput = sc.next().toLowerCase();
System.out.print("Please enter the name of the city : ");
String cityInput = sc.next().toLowerCase();
System.out.println("\n-----------------------------");
switch(countryInput) {
case "iran" :
System.out.print("+98 ");
break;
case "us" :
System.out.print("+1 ");
break;
default: System.out.print("ERROR: the entered country doesn't exist in program database!");
}
if(countryInput=="iran") {
switch(cityInput) {
case "tabriz" :
System.out.print("411");
break;
case "tehran" :
System.out.print("21");
break;
case "mashhad" :
System.out.print("511");
break;
default : System.out.print("\nERROR: the entered city doesn't exist in program database!");
}
}
if(countryInput=="us") {
System.out.print("(Sorry, the US cities aren't avalable!)");
}
System.out.print("\n-----------------------------\nProgrammer: user3891619");
}
}
And also this one. The program never says "Password is wrong" even when is necessary:
import java.util.Scanner;
public class Pass {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int pass = 1234 ;
System.out.print("Please enter your password: ");
if(sc.hasNextInt() && sc.nextInt() == pass) {
System.out.println("The password was successfully entered.");
}
else {
if(sc.hasNextInt()) {
System.out.println("The password is wrong.");
}
else {
System.out.println("Password format is incorrect.");
}
}
}
}
Your post has 2 questions.
For the second one it's easy. When you call sc.hasNextInt() it verifies if there is an integer in the next section. Calling sc.nextInt() will read this integer and put the read cursor behind it. If you again call hasNextInt() it will verify if there is a second integer value which is not the case in your situation.
Your if structure should be:
if (sc.hasNextInt())
{
if (sc.nextInt()==pass)
System.out.println("The password was successfully entered.");
else
System.out.println("The password is wrong.");
} else {
System.out.println("Password format is incorrect.");
}
Try with:
while (sc.hasNextInt(){
if(sc.nextInt().equals(pass)) {
System.out.println("The password was successfully entered."); }
else{
if(sc.hasNextInt()){System.out.println("The password is wrong.");}
else{System.out.println("Password format is incorrect.");}
}}
You have to use .equals for Strings instead of ==
Yes Ben Green is right. Please use .equals when comparing strings.
countryInput.equals("something")
Please read this to find your answer.
What is the difference between == vs equals() in Java?
Related
Just beginning to learn java and I am trying to code a simple password check that gives you tries if you type the incorrect password. The problem is when I type the incorrect password and followed by the correct password it still says its the wrong password.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Tell us the Password");
while(true) {
String password = scanner.nextLine();
if (password.equalsIgnoreCase("Happy")) {
System.out.println("Correct password");
break;
}
else {
for (int i =6; i>0;i--) {
System.out.println("Incorrect password ");
System.out.println(+ i + " Trys left");
password= scanner.nextLine();
}
}
System.out.println("No more tries");
System.out.println("Program exits");
break;
}
}
I want the program to check if the password is correct or incorrect.
Once you entered the wrong password, code flow stuck in the for loop and remain there for available iterations, no comparison with entered password is going on there so you need to modify the flow. One way to do so as per your initial code posted is
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Tell us the Password");
int tryCountForFailure = 6;
while (true) {
String password = scanner.nextLine();
if (password.equalsIgnoreCase("Happy")) {
System.out.println("Correct password");
break;
} else {
System.out.println("Incorrect password ");
System.out.println(tryCountForFailure + " Trys left");
tryCountForFailure--;
if (tryCountForFailure == 0) {
System.out.println("No more trys");
System.out.println("Program exits");
break;
}
}
}
scanner.close();
}
In your code, the loop gets stuck in the Else statement. Let's run through the logic.
The program asks for the password and stores it in a password String.
The program check's if that password is right, if it is the program stops and if not it continues to the else statement.
The program uses a for statement to run this block of code 6 times:
System.out.println("Incorrect password ");
System.out.println(+ i + " Trys left");
password = scanner.nextLine();
The problem is even if you enter a correct String for the password field, it never checks if that value is correct. You would be better of refactoring your code so the logic is sound. Let's run through what should happen.
Program defines a variable named count and set's it to 0.
The program uses a while loop to ask if count is less than 6.
The program takes in a password String with a scanner.
The program checks if that password String is equal to the correct password, if yes, it breaks and,
If it does not equal the correct password it adds one to count
Scanner scanner = new Scanner(System.in);
System.out.println("Tell us the Password");
String password = scanner.nextLine();
if (password.equalsIgnoreCase("Happy")) {
System.out.println("Correct password");
break;
} else {
count++
}
}
I recently started java programming
but I have a problem
i want to write a program. I have a password, I ask the user of the program to enter the password
I want: if the person entered a string, I tell him that please don't enter string
and if the password was right and the type of the password that he entered(int) was right, I tell him OK.
in the test of the program, my problem is that when I entered a wrong password and expect that the program tell me that the pass is wrong, the program just tell me nothing !!
here is my code :
int pass = 123 ;
Scanner password = new Scanner(System.in);
System.out.println("Please Enter Your Password : ");
if (password.hasNextInt() && password.nextInt()==pass)
{
System.out.println("ok");
}
else if (password.hasNextInt())
{
System.out.println("wrong pass");
}
else
{
System.out.println("wrong type");
}
You are using hasNextInt() From Java docs.
Returns true if the next token in this scanner's input can be
interpreted as an int value
So you are asking twice for the input.
Example
Input:
1234 (first Input)
1234 (Then hasNextInt() is asking for input again)
OutPut :
wrong pass
So I made this simple snippet for you can use
Scanner password = new Scanner(System.in);
System.out.println("Please Enter Your Password : ");
int pass = 123;
try {
int myInput = password.nextInt();
if (myInput == pass) {
System.out.println("ok");
}else{
System.out.println("wrong pass");
}
}catch (java.util.InputMismatchException e) {
System.out.println("wrong type");
}
The problem is that Scanner methods like nextInt() consume input that's then no longer available to later Scanner calls.
int pass = 123 ;
Scanner password = new Scanner(System.in);
System.out.println("Please Enter Your Password : ");
if (password.hasNextInt() && password.nextInt()==pass) // line A
{
System.out.println("ok");
}
else if (password.hasNextInt()) // line B
{
System.out.println("wrong pass");
}
else
{
System.out.println("wrong type");
}
So in case of entering a wrong password, e.g. 4321, what happens?
Line A checks password.hasNextInt() as the first half of your condition. The Scanner doesn't know that right now and waits for your console input. You enter 4321, and now the Scanner can check whether that's a valid number (and it does so without consuming the 4321, so that it's still available). It is, so the program continues to the next part of the condition (side remark: were it abc, that first part would be false, and Java would already know that the combined password.hasNextInt() && password.nextInt()==pass condition would be false, without a need to go into the second half, thus not consuming the entry).
Line A now checks the second half password.nextInt()==pass. This calls nextInt(), returning the integer 4321 and consuming the input. Comparing this against your number 123 gives false, so the condition doesn't match. That's what you want so far.
Now in line B you want to check for the case of a number not being 123. But your condition password.hasNextInt() no longer sees the 4321 we entered, as that has been consumed in line A. So it waits for the next input. That's the problem, you're still calling hasNextInt() after consuming the input with nextInt().
You can change your program like this:
int pass = 123 ;
Scanner password = new Scanner(System.in);
System.out.println("Please Enter Your Password : ");
if (password.hasNextInt()) {
if (password.nextInt()==pass) {
System.out.println("ok");
} else {
System.out.println("wrong pass");
}
} else {
pass.next(); // consume the invalid entry
System.out.println("wrong type");
}
[ I reformatted the code snippet in a more Java-typical style, doesn't change the functionality of course, but looks more familiar to me. ]
Of course, Gatusko's exception-based approach works as well, and personally I'd do it his way, but maybe you don't feel comfortable with exceptions right now, so I stayed as close to your approach as possible.
You can use the following piece of code.
public static void main(String[] args){
int pass = 123 ;
Scanner password = new Scanner(System.in);
System.out.println("Please Enter Your Password : ");
if (password.hasNextInt())
{
if(password.nextInt()==pass) {
System.out.println("ok");
}
else {
System.out.println("Wrong password");
}
}
else
{
System.out.println("wrong type");
}
}
What about a while?
int MAX_TRIES = 3
int currentTries = 0;
while (password.hasNextInt() && currentTries < MAX_TRIES) {
if (password.nextInt()==pass) {
// OK!
} else {
// Wrong!
}
currentTries++;
}
if (currentTries == MAX_TRIES) {
// You tried too much
} else {
// Password was a string
}
Try this code, if the input is not an integer then it will throw NumberFormatException, which is caught and displayed.
public static void main(String[] args){
int pass = 123 ;
Scanner password = new Scanner(System.in);
System.out.println("Please Enter Your Password : ");
String enteredPassword ="";
if(password.hasNext() && (enteredPassword = password.next()) !=null){
try{
if(Integer.parseInt(enteredPassword) == pass){
System.out.println("ok");
}else{
System.out.println("wrong pass");
}
}catch (NumberFormatException nfe){
System.out.println("wrong type");
}
}
}
I'm still relatively new to Java and wanted to try out some new stuff related to strings. I tried to write a code for the user to enter a password between 4-12 characters, and so far it worked fine. But during the process, I had to make little fixes here and there, and honestly it does look pretty messy, like a puzzle where all pieces fit but don't make one whole picture. I want my code to be something more "optimized" so I can have an idea of how codes like this one works, you know, just for future reference. So any help appreciated, please take a look at my code and see if there's anything that can be improved. Thanks!
import static java.lang.System.*;
import java.util.Scanner;
public class PasswordWithLimit {
public static void main (String[] args){
Scanner scan = new Scanner (in);
out.print("Enter your password(4-12 characters): ");
String pass = scan.nextLine () + " ";
char check = pass.charAt (11);
if (pass.indexOf (" ") == 3){
out.println("Please enter a valid password: ");
}
if (Character.isSpaceChar(check) || Character.isWhitespace(check)){
out.println("Your password is " + pass);
}
else{
out.println("Please enter a valid password");
}
}
}
I would recommend using the String's length property. This example prompts the user to enter their password and continues asking them until they have entered something which meets the requirements.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter your password (4 to 12 characters)"); // Prompt the user
boolean valid = false;
while (!valid) {
String password = in.nextLine();
if (password.length() > 3 && password.length() < 13) {
valid = true; // Length between 4 and 12, we can stop asking.
System.out.println("Your password is " + password);
} else {
System.out.print("Please enter a valid password: "); // Invalid length, ask again.
}
}
in.close();
}
The title is deceiving however I didn't really know how to ask this.
I am playing around with java. This is my code:
package zodiac;
import java.util.Scanner;
public class Zodiac {
public static void main(String[] args) {
Scanner username = new Scanner(System.in);
String uname;
System.out.println("Please enter your username: ");
uname = username.nextLine();
boolean test = (uname.length() <= 3);
int trip = 0;
while (trip == 0) {
trip++;
if (test) {
trip = 0;
System.out.println("Sorry username is too short try again");
uname = username.next();
}
else {
System.out.println("Welcome Mr/Mrs: " + uname);
}
}
}
}
what i'm trying to do is prompt the user to enter their username and once they do check if the name is less than or equal to 3 make them type the username again, if the username if more than 3 chars print welcome mr/mrs blablabla
at the moment if the username if more than 3 chars it prints out the welcome message, however if you enter 3 or less chars it tells you to enter the username again and if you type a username with more than 3 chars afterwords it keeps telling the user that the password is too short.
How can i fix this. I have just recently started studying java at university however my teachers lack motivation to teach so i have to result to the internet, thank you.
There are two things that you might want to think about in your code:
don't use an integer to stop looping if a boolean would be sufficient
a do-while loop might be more appropriate for your case (you don't have to rewrite code that way!
Now to your question: You are not checking the required minimum length of the inserted string in your loop again! This code might help you to understand all of the points i mentioned:
public static void main(String[] args) {
Scanner username = new Scanner(System.in);
String uname;
System.out.println("Please enter your username: ");
boolean tooShort = true;
do {
uname = username.next();
if (uname.length() <= 3)
System.out.println("Sorry username is too short try again");
else {
System.out.println("Welcome Mr/Mrs: " + uname);
tooShort = false;
}
} while (tooShort);
username.close();
}
insert boolean test = (uname.length() <= 3) in your loop
Helllo can somebody tell my why it doesn't tell my that the password is invalid, when I don't write the valid password?
import java.util.Scanner;
public class Password {
private static Scanner in;
public static void main(String[] args) {
System.out.println("Please enter the password:");
in = new Scanner (System.in);
String pass;
pass = in.nextLine();
if(pass.length() < 4){
System.out.println("The password is too short");
} else if(pass.length() > 9){
System.out.println("The password is too long");
}
if(pass.equalsIgnoreCase("hudhud")){
System.out.println("Welcome BOSS");
while (!pass.equals("hudhud")){
System.out.println("The password is invalid");
}
}
}
}
Test cases:
Input: foo
Output: The password is too short
Input: foobar
Output:
Input: foobarfoobar
Output: The password is too long
Input: hudhud
Output: Welcome BOSS
Your while statement
while (!pass.equals("hudhud")){
System.out.println("The password is invalid");
}
is dead code - it cannot be reached. You check if pass equals hudhud. Inside that check, you have a while loop without a break statement testing if the password doesn't equal hudhud. At this point, it cannot equal anything other than hudhud.
Note that nothing is printed to the screen when the password is between 4 and 9 characters and not equal to hudhud. If you're trying to change that, add an else to the if(pass.equalsIgnoreCase("hudhud")) check.