Hash Set giving error when comparing an input - java

Trying to check a password against values in a hash set. The error appears to be in the myset.contains but cant see why.
Set<String> myset = new HashSet<>();
myset.add("Apples");
myset.add("Bananas");
String inputPass;
Scanner input = new Scanner(System.in);
System.out.println("Fruit?: ");
inputPass = input.nextLine();
if (inputPass.equals(myset.contains)) {
// Lecturer.printMe();
System.out.println("Welcome");
}
else {
System.out.println("ACCESS DENIED");
}
Would appreciate some guidance.

"contains" is a method, not a field. Also, it accepts an instance of T (in this case, a String) as a parameter.

You use of Set#contains does not look right to me. Try using this version:
if (myset.contains(inputPass)) {
System.out.println("Welcome");
}
else {
System.out.println("ACCESS DENIED");
}

Related

How to create custom exception for just Integers

I want to create a class that will serve me as an exception. I will give you two examples of how I tried. I've been looking for it but I can't find an example of how to put this into practice, or it doesn't work for me.
This is my method where user choose flight by ID, I want to throw an exception if a program user enters a String.
Code:
#Override
public void choosePassenger(ArrayList<Passenger> passengerList) {
System.out.println("Choose passenger by ID: ");
try {
int pickedPassenger = scanner.nextInt();
for (Passenger tempUser : passengerList) {
if (pickedPassenger == tempUser.getId()) {
System.out.println("You picked passenger: " + tempUser.getFirstName() + ", "
+ tempUser.getLastName() + ". Balance is: " + tempUser.getBalance());
selectedPassenger = tempUser;
break;
}
}
} catch (InputMismatchException e) {
System.out.println("Wrong input! Try again");
scanner.nextLine();
}
}
I tried on that way but after program show me message Wrong input! Try again it goes to another method not giving me chance to enter valid input
Also, how I can create exception here for just Strings?
System.out.print("Add name of passenger: ");
passenger.setFirstName(scanner.nextLine());
This is part of code that enable program user to create new user, he is adding here name, I want to create exception so if program user add integer for name I want to show him an exception
EDIT:
If I delete scanner.nextLine(); program stops but first print me my own exception message then print me message from next method and then InputMissMatchException for that method on his own because I input string instead of integer
If you want the user to try again, you can keep them in an infinite loop that breaks after correct input.
Editing as per #DevilsHnd observation. You cannot use scanner.nextInt() in this manner as it will read without user being prompted for input and it results in being stuck in an infinite loop.
You can then use nextLine() and validate the input is a number like this:
while(true) {
try {
int pickedPassenger = Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException e) {
System.out.println("Wrong input! Try again");
}
}
For restricting input to a non numeral value as you want for the name, you would have to check if the value entered is a number (there is no scanner method to restrict reading to non numeral values)
Most elegant way in my opinion is to use an external library that has this like Apache Commons:
while(true) {
String firstName = scanner.nextLine();
if (!NumberUtils.isCreatable(firstName )) {
passenger.setFirstName(firstName );
break;
} else {
System.out.println("Value cannot be a number!");
}
}
However, if you cannot import external libraries, simplest way to do this is by using built in Java Integer.parseInt() function(although you might want to consider regex - see link below):
while(true) {
String firstName = scanner.nextLine();
try {
Integer.parseInt(firstName);
System.out.println("Value cannot be a number!");
} catch (NumberFormatException e) {
passenger.setFirstName();
break;
}
}
For more options on checking if a value is a number (like regex) check this:
https://www.baeldung.com/java-check-string-number

Catch exceptions in a do-while loop?

Can someone explain and help me fix this program.
import java.util.*;
import java.io.*;
public class test {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
boolean clear;
int in = 0;
do {
clear = true;
try {
in = key.nextInt();
} catch (InputMismatchException e) {
System.out.println("Invalid");
clear = false;
}
} while (clear == false);
String stringIn = Integer.toString(in);
String[] dec = stringIn.split("");
for (int i = 1; i < (dec.length); i++) {
System.out.print(dec[i] + " ");
}
}
}
Whenever I enter a invalid input instead of an int, my program keeps looping "Invalid" instead of giving the option to enter a new value for in.
The problem is that if the scanner fails to find an input in the correct format, it will throw an exception and not read the input.
Because the scanner does not read the invalid int input, the next time nextInt is called, it will try to read the invalid input again, and miserably fails at it, printing another "invalid!"
So you need to read the input afterwards if it finds an invalid int:
// do this in the catch block:
key.next();
This makes sure that the next token is read.
Full code:
Scanner key = new Scanner(System.in);
boolean clear;
int in = 0;
do {
clear = true;
try {
in = key.nextInt();
} catch (InputMismatchException e) {
System.out.println("Invalid");
clear = false;
key.next();
}
} while (clear == false);
String stringIn = Integer.toString(in);
String[] dec = stringIn.split("");
for (int i = 1; i < (dec.length); i++) {
System.out.print(dec[i] + " ");
}
Check the API of the nextInt method:
This method will throw InputMismatchException if the next token cannot be translated into a valid int value as described below. If the translation is successful, the scanner advances past the input that matched.
Meaning, that if it's not successful - it will not advance and will try to execute nextInt over the illegal token over and over again failing every time.
Try adding next() into the exception catch clause, it should skip the token and read the next one then. next() reads a String, so it does not really care about the formatting, and will allow you to advance the position in the stream to read the next token.
The problem is that you are writing to the console inside the catch, so then when you call key.nextInt() in the try the program reads the value you print to the console, so an easy way to solve this is to add a line like: key.nextLine() inside the catch and that will solve your problem.

Return to previous spot in loop after try catch?

} else if (selectionKey == 2) {
System.out.println("Please enter the item name");
if (s.nextLine() != "") {
item = s.nextLine();
}
try {
ZybezChecker zb = new ZybezChecker(item);
zb.getAveragePrice();
System.out.println(zb.toString());
} catch(Exception e) {
System.out.println("Something went wrong. Perhaps an invalid item name?");
}
That's my code atm. How do I return back to the if statement and continue the loop after it catches?
You could embed it in a loop like,
for (;;) { // <-- start an infinite loop
System.out.println("Please enter the item name");
if (s.nextLine() != "") {
item = s.nextLine();
}
try {
ZybezChecker zb = new ZybezChecker(item);
zb.getAveragePrice();
System.out.println(zb.toString());
break; // <-- terminate the infinite loop.
} catch(Exception e) {
System.out.println("Something went wrong. Perhaps an "
+ "invalid item name?");
e.printStackTrace(); // <-- tell them what went wrong.
}
}
I think (if I understand your question and code correctly) that what you want is a loop containing the s.nextLine(). Note that I am assuming several things here:
s is a Scanner or something equivalent that reads input from the user
an exception is thrown if the user enters invalid input
you want to keep asking the user for input until they enter something valid
If this is the case, then you should create a loop like this:
while (true) {
System.out.println("Please enter the item name");
if (s.nextLine() != "") {
item = s.nextLine();
}
try {
ZybezChecker zb = new ZybezChecker(item);
zb.getAveragePrice();
System.out.println(zb.toString());
break;
} catch(Exception e) {
System.out.println("Something went wrong. Perhaps an invalid item name?");
}
}
Also, why are you calling nextLine() twice? When you call it the first time, it will read a line from the scanner. When you call it again, it will not return the same line; it will instead wait for a new line. This means the user has to enter some random string, then enter the actual value. Finally, you should NEVER use == or != on Strings. Since they are reference types, you are essentially checking if they occupy the same location in memory, rather than if they are equal. Use s.nextLine().equals("") instead.

Java: How to Automatically Restart A Console Program If The "Else" Statement Is Triggered

I am making a simple program that asks for a password before you can start the program. When my user inputs the wrong password, they get an "Access Denied," warning. I achieve this using an If/Else Statement. What I want to be able to do is to re-run my program if they enter the wrong password, as they cannot type in the console again if they get it wrong.
Here is my workspace:
import java.util.Scanner;
public class PasswordProtected {
public static void main (String args[]){
Scanner Password = new Scanner (System.in);
String mainpassword, userInput;
mainpassword = ("Jacob");
System.out.println("Please enter the password to continue.");
userInput = Password.nextLine();
System.out.println("Verifying Password");
if (userInput.equals(mainpassword)){
System.out.println("Access Granted");
System.out.println("Welcome!");
}else{
System.out.println("Access Denied");
}
}
}
I do realize that I could copy some thing like this over and over again, however, it is a waste of space is is not unlimited.
System.out.println("Please enter the password to continue.");
userInput = Password.nextLine();
System.out.println("Verifying Password");
if (userInput.equals(mainpassword)){
System.out.println("Access Granted");
System.out.println("Welcome!");
}else{
System.out.println("Access Denied");
}
}
Please note that I am new at programming, and may need a bit of extra help.
If the Else Statement is triggered, how can I fully restart my program without the use of manually clicking the run button again?
You don't need to restart your program. Use a loop to ask for the password again if it is incorrect. For example in semi-pseudo code with while statement:
userInput = input.nextLine();
while ( !userInput.equals(mainpassword) ){
userInput = input.nextLine();
}
Try while(true) loop
String mainpassword = ("Jacob");
String userInput = null;
Scanner Password = new Scanner (System.in);
while(true) {
userInput = Password.nextLine();
if (userInput.equals(mainpassword)){
break;
} else {
System.out.println("Access Denied");
}
}
System.out.println("Access Granted");
System.out.println("Welcome!");
If you still feel to restart any Java program, then the main() method can be called from anywhere else in your code. You can just call this method, passing in any necessary String parameters. Use a thread to do so, as below
Thread t = new Thread() {
public void run() {
String[] args = { };
PasswordProtected.main(args);
}
};
t.start();
If you want to re-launch your application in a new process, you can use
Runtime.getRuntime().exec(...);

Pass a string from one class to another in java

I'm trying to pass a String from one class to another class but the result I'm getting is 'null'. I want to pass the String username from LoginFrame to HomeworkFrame;
HomeworkFrame:
public void loadSubjects (){
String item;
try{
System.out.println(username);
Scanner f = new Scanner (new FileReader (username + " " + "Subjects" + ".txt"));
while(f.hasNext()){
item = f.nextLine();
chSubjects.add(item);
}
f.close();
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Subjects cannot be loaded!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
LoginFrame:
public void loginUser(){
r = new Registration();
h = new HomeworkFrame();
l = new Login();
l.username = txtUser.getText();
l.password = txtPass.getText();
try{
String line;
boolean passwordFound = false ;
BufferedReader f = new BufferedReader(new FileReader(l.username + ".txt"));
while((line = f.readLine()) != null){
if(line.equals(l.password)){
passwordFound = true;
}
}
if(passwordFound){
h.username = l.username;
dispose();
m.setSize(700,600);
m.setLocation(100,100);
m.setVisible(true);
}else{
JOptionPane.showMessageDialog(null, "Wrong information!", "Error", JOptionPane.ERROR_MESSAGE);
}
f.close();
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Wrong information!", "Error", JOptionPane.ERROR_MESSAGE);
}
}
Obviously I'm getting the error "Subjects cannot be loaded" as the username is null(I checked it by using the println method).
In case problems like this you have to track your variables/fields from the place you've noticed your 'username' field is null. Next steps should be:
Check what operations you do on 'h' object before you call the loadObjects() method and if any then check what influence they have on username field in HomeWorkFrame (using println or a debugger).
Check if your passwordFound in LoginFrame is true (because if it's false it doesn't assign a value to h.username)
If it's false check if your password's been retrieved from a file (using same println statement)
This kind of scenario should help you finding most of 'null' bugs.
Try to check first, which type of Exception you get.
May be the file is not existing or the list is null or....
Is a format problem : put a \ before your space in pathString : "\ "
You have to write it "\ Subjects.txt", without '+' between.
public class LoginFrame{
private HomeworkFrame hw;
public void doSomething(){
String username = "your username";
hw = new HomeworkFrame(username);
}
}
public class HomeworkFrame{
public HomeworkFrame(String username){
doSomething with 'username'
}
}
Ans to your question! :)
If System.out.println(username); displays null this means that
1.username variable is not initialized and left.
2.value is not assigned to it properly.
3.It might be a static variable and you are changing the value of it.
Please check all these conditions and please give that part of the code from where the loadSubjects() is being called, and not the body of that method as you have provioded it already.
Also all those parts of code where the username is initialized,assigned,modified.
It is required to specify or pass the value otherwise it will definitely give Null as it will not find any value to execute.

Categories

Resources