How to loop my password acceptance program - java

I am fairly new to java(as in started 2 days ago) and i would like to know how i could loop this program. I tried to do the do while function but it keeps saying that my variables cannot be resolved as a variable.
This is the code:
class GS1 {
public static void main(String[]args){
do {
System.out.println("Enter your password");
Scanner F_pass = new Scanner(System.in);
String f_word= F_pass.next();
System.out.println("Verify Password");
Scanner Pass = new Scanner(System.in);
String word = Pass.next();
} while(f_word != word);
}
}

This seems like it would work. Typically you only need one instance of a Scanner object, and it will work throughout the entire class--depending on the scope that you use.
public static void main(String[] args)
{
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
String origPass = "Original";
String verify = "Verify";
while(!origPass.equals(verify)){
System.out.println("Enter your password");
origPass = input.nextLine();
System.out.println("Verify your password");
verify = input.nextLine();
}
}
All I did was compare the values of the two string. If they are not the same, your program will repeat until the condition is satisfied. You can add a print statement to let the user know it was an incorrect password should they not have matching values. Hope this is what you were looking for.

Related

How to make java scanner accept more than one string input?

Hello i'm currently a beginner in Java. The code below is a while loop that will keep executing until the user inputs something other than "yes". Is there a way to make the scanner accept more than one answer? E.g. yes,y,sure,test1,test2 etc.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String ans = "yes";
while (ans.equals("yes"))
{
System.out.print("Test ");
ans = in.nextLine();
}
}
}
Use the or operator in your expression
while (ans.equals("yes") || ans.equals("sure") || ans.equals("test1"))
{
System.out.print("Test ");
ans = in.nextLine();
}
But if you are going to include many more options, it's better to provide a method that takes the input as argument, evaluates and returns True if the input is accepted.
Don't compare the user input against a value as loop condition?!
Respectively: change that loop condition to something like
while(! ans.trim().isEmpty()) {
In other words: keep looping while the user enters anything (so the loop stops when the user just hits enter).
You are looking for a method to check whether a given string is included in a List of string values. There are different ways to achieve this, one would be the use of the ArrayList contains() method to check whether your userinput in appears in a List of i.e. 'positive' answers you've defined.
Using ArrayList, your code could look like this:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
ArrayList<String> positiveAnswers = new ArrayList<String>();
positiveAnswers.add("yes");
positiveAnswers.add("sure");
positiveAnswers.add("y");
Scanner in = new Scanner(System.in);
String ans = "yes";
while (positiveAnswers.contains(ans))
{
System.out.print("Test ");
ans = in.nextLine();
}
}
}

My code isn't working

I am a beginner programmer and i am trying a program for my father.
import java.util.*;
import java.lang.*;
import java.io.*;
class Employee
{
String m1,m2,m3,m4,m5,m6,m7;
void main()
{
Scanner w=new Scanner(System.in);
Scanner n=new Scanner(System.in);
System.out.println("Please enter your name ");
String name=w.nextLine();
System.out.println("Please choose your client");
System.out.println("1 - XXXXXX");
int client=n.nextInt();
m1=name;//Storing name
if(client==1)//If statement storing client
{
m2="XXXXXX";
}
else
{
System.out.println("You have entered a wrong choice");
return;
}
String msg=m1+"\t"+m2;
System.out.println(msg);
}
}
This Code will give the output "as you have entered a wrong choice'"
It jumps to elsse statement. What is the error and is there an easier way to run this program. Thanks
Could yo please inform me on my error as
Ok try this code:
import java.util.Scanner;
public class Try
{
static String m1,m2,m3,m4,m5,m6,m7;
public static void main(String[] args)
{
Scanner w=new Scanner(System.in);
System.out.println("Please enter your name ");
String name=w.nextLine();
System.out.println("Please choose your client");
System.out.println("1 - XXXXXX");
int client=w.nextInt();
m1=name;//Storing name
if(client==1)//If statement storing client
{
m2="XXXXXX";
}
else
{
System.out.println("You have entered a wrong choice");
return;
}
String msg=m1+"\t"+m2;
System.out.println(msg);
}
}
You have missed you main method signature. In Java there is a specification of main method. Your main method should be like
public static void main(String []args){
}
In your case you main method should be
public static void main(String args[]) {
String m1, m2, m3, m4, m5, m6, m7;
Scanner w = new Scanner(System.in);
Scanner n = new Scanner(System.in);
System.out.println("Please enter your name ");
String name = w.nextLine();
System.out.println("Please choose your client");
System.out.println("1 - XXXXXX");
int client = n.nextInt();
m1 = name;//Storing name
if (client == 1)//If statement storing client
{
m2 = "XXXXXX";
} else {
System.out.println("You have entered a wrong choice");
return;
}
String msg = m1 + "\t" + m2;
System.out.println(msg);
}
Your problem are the 2 scanners.
Because a scanner work with an iterator, that keep the position inside the given inputstream (in this case), when you instantiate the 2 scanners, they both set their iterator at the same position into the stream, then you use "w.nextLine();", and the first scanner advances trough the stream returning the first line, as you wish, but the second scanner, that you haven't used, is still at the beginning of the stream, so basically when you use n.nextInt();, the scanner tries to parse your name as int, and it's strange that it doesn't throws an InputMismatchException, as it should do ("https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt%28%29").
Rework your code as #Sarthak Mittal suggested and it should work.
PS: keep in mind indentation, it's important, really
First:
void main()
There is no such thing in Java. It should be,
public static void main(String[] args)
To know the meanings of public, static, String[] args read this: Explanation of 'String args[]' and static in 'public static void main(String[] args)'
Secondly,
int client = n.nextInt();
The value inside client depends on your input. If you input 2 or 3 instead of 1, your code'll definitely go to the else part. So make sure your input is 1.
Thirdly,
Get rid of the extra scanner. You need only one.
The rest of your code is ok.

Trying to write a very simple program involving a password (java)

So I tried out having a password check in my program, the goal is, if the user types the correct password then the program will reply: "You Pass", if not the "You're wrong". The problem is Eclipse tells me that "Fish (that's the password) cannot be resolved to a variable"
import java.util.Scanner;
public class Password {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
String password;
password = Fish;
System.out.println("What is the password? ");
scan.nextLine();
if (scan.equals(password)) {
System.out.println("You pass!");
}
else {
System.out.println("You're wrong!");
}
}
}
I tried resolving the issue in Eclipse's way, but with their method I get the wrong password when I type it after running the program:
import java.util.Scanner;
public class Password {
private static final String Fish = null;
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
String password;
password = Fish;
System.out.println("What is the password? ");
scan.nextLine();
if (scan.equals(password)) {
System.out.println("You pass!");
}
else {
System.out.println("You're wrong!");
}
}
}
I tried looking this up online, I'm actually reading Java Programming for Dummies, and still no luck, hopefully you can help me, I'd appreciate it!
Thanks!
You have wriiten some wrong syntaxes for it.Try this code.I have added necessary comments to let you make undersatand that what I have done in the following code.
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
String password;
password = "Fish"; // assigning value to String password
System.out.println("enter value");
String temp=scan.nextLine(); //scanner takes nextline entered and assign it to temp
// if (scan.equals(password)) is wrong ,you want to compare value taken by scanner , what you have wriiten is incorrect. scan is object of Scanner.Not value taken by it
if(temp.equals(password)) //if entered value eqauls your assigned password value
{
System.out.println("You pass!"); // else print you pass
}
else
{
System.out.println("You're wrong!"); //else print "you are wrong"
}
First of all,you're never reading your input in a variable!and then you're trying to check equality between the "scan" object which is of type Scanner.Instead read input "scan.nextLine();" in a variable say "var" and then call var.equals(password).Please also check that your String "Fish" is null initially which will give you a NullPointerException!
if (isValid(password))
{
System.out.println("You pass!");
}
else
{
System.out.println("You're wrong!");
}
Welcome to the Java World!
In your program you are making a small mistake by calling the equals on a Scanner object.
Also remember to close the close-able scanner resource once you are done with it.
Please refer the code below.
import java.util.Scanner;
public class Password {
private static final String Fish = "Fish";
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println("What is the password? ");
if (scan.nextLine().equals(Fish)) {
System.out.println("You pass!");
}
else {
System.out.println("You're wrong!");
}
}
}

Why does it not ask me for input?

import java.util.Scanner;
class Tutorial {
public static void main (String args[]){
System.out.println("Who goes there?");
Scanner name = new Scanner(System.in); ## I am asking for input form user but it does not take imput
if (name.equals("me") || name.equals("Me") ){
System.out.println("Well, good for you smartass.");
}else System.out.println("Well good meet");
}
}
Why does the program run the else and not ask for my input?
You should read your input by using scanner.nextLine():
Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine();
if (name.equals("me") || name.equals("Me"))
{
System.out.println("Well, good for you smartass.");
} else {
System.out.println("Well good meet");
}
scanner.close();
You merely created a Scanner but did not tell it to read something from the standard input. You can do that by calling scanner.next() to read a token scanner.nextLine() to read a line, etc. As well you are comparing a Scanner to a String in the if-statement.
import java.util.Scanner;
class Tutorial {
public static void main (String args[]){
System.out.println("Who goes there?");
Scanner s = new Scanner(System.in);
String name = s.next(); // get the token
if (name.equals("me") || name.equals("Me") ){
System.out.println("Well, good for you smartass.");
} else System.out.println("Well good meet");
}
}
You've only created an instance of the Scanner object. You need to invoke a method such as Scanner#nextLine() to read input and then compare the read value to "me" or "Me".
Example:
Scanner name = new Scanner(System.in);
String input = name.nextLine();
if (...) // Compare input to something here.
You might want to use String#equalsIgnoreCase for case-insensitive matching too.

Looping in Java(Beginners)

I have to use a loop in my code so that when someone enters yes, they can re-enter their names as many times as they want, but I have no idea how to do this. Any help is appreciated, here is my code:
public static void main(String [] args)
{
// Create a Scanner object to read input.
Scanner keyboard = new Scanner(System.in);
//Get the user's name.
System.out.print("What is your name?");
String name = keyboard.nextLine();
System.out.println("Hello there," + name);
System.out.println("Would you like to enter another name? Please enter Yes Or No.");
String reply = keyboard.nextLine();
if (reply == "yes")
{
}
}
}
This reply == "yes" is not how you compare Strings in Java. This compares there memory locations, not there contents (and it's unlikely there memory locations are going to be equal).
Instead you need to use reply.equals("yes") or if you don't care about doing a case comparison, you can use reply.equalsIgnoreCase("yes") instead
do {
// The remainder of your code...
} while (reply.equalsIgnoreCase("yes"));
Updated
You may also wish to have a read through The while and do-while statements and The for Statement, which covers the basics of looping in Java
Use a do-while loop:
public static void main(String[] args) {
// Create a Scanner object to read input.
Scanner keyboard = new Scanner(System.in);
do {
//Get the user's name.
System.out.print("What is your name?");
String name = keyboard.nextLine();
System.out.println("Hello there," + name);
System.out.println("Would you like to enter another name? Please enter Yes Or No.");
} while (keyboard.nextLine().equalsIgnoreCase("yes"));
System.out.println("Bye!");
keyboard.close();
}
}
use this
import java.util.*;
public class prob13 {
public static void main(String [] args)
{
// Create a Scanner object to read input.
Scanner keyboard = new Scanner(System.in);
//Get the user's name.
while(true){
System.out.print("What is your name?");
String name = keyboard.nextLine();
System.out.println("Hello there," + name);
System.out.println("Would you like to enter another name? Please enter Yes Or No.");
String reply = keyboard.nextLine();
if(reply.equals("no"))
break;
}
}
}
The reason for this is to loop through as long as the answer is not no.
or you could use this if you want the answer to always be yes
import java.util.*;
public class prob13 {
public static void main(String [] args)
{
// Create a Scanner object to read input.
Scanner keyboard = new Scanner(System.in);
String reply="yes";
//Get the user's name.
while(reply.equals("yes")){
System.out.print("What is your name?");
String name = keyboard.nextLine();
System.out.println("Hello there," + name);
System.out.println("Would you like to enter another name? Please enter Yes Or No.");
reply = keyboard.nextLine();
}
}
}
I think this will work (untested):
public static Scanner keyboard = new Scanner(System.in); // global
public static void main(String [] args)
{
getName();
}
public static void getName()
{
System.out.print("What is your name?");
String name = keyboard.nextLine();
System.out.println("Hello there," + name);
rerun();
}
public static void rerun()
{
System.out.println("Would you like to enter another name? Please enter \"yes\" or \"no\".");
String reply = keyboard.nextLine();
if (reply.equals("yes")) getName();
else System.exit();
}
}
First we call the getName() method and run through that once. Then we make a call to the rerun() method. This method will test if we want to re-run the program. If the user types in "yes", then we repeat the whole process. If we type in anything besides "yes", the program quits.
Besides the fact that your code is unfinished, the only real problem with your code is that you try to compare strings with the == operator. See MadProgrammer's answer as to why that is wrong.
The simplest (and probably clearest) way is to wrap what you want to repeat in a do-while statement:
public static void main(String [] args)
{
// Create a Scanner object to read input.
Scanner keyboard = new Scanner(System.in);
String reply;
do {
//Get the user's name.
System.out.print("What is your name?");
String name = keyboard.nextLine();
System.out.println("Hello there," + name);
System.out.println("Would you like to enter another name? Please enter Yes Or No.");
reply = keyboard.nextLine();
} while ("yes".equals(reply));
}
}
The reply variable must be declared before the block, because it is accessed in the loop condition (a variable is only visible in the block it is declared in, so if reply were declared in the loop, it would not be available to the loop condition).
I changed the loop condition because the == operator compares Strings by reference, i.e. it will check whether both sides point to the same String object. The equals method, in contrast, checks that the content of the Strings is equal (i.e. they contain the same characters in the same order).

Categories

Resources