Pass a string from one class to another in java - 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.

Related

Java help me Login with txt File

I do not understand why I always get the result is false !
I tried sysout both input and split []. They are all the same
,Also I can not use this.dispose ()
public void actionPerformed(ActionEvent e) {
String record = null;
FileReader in = null;
try {
in = new FileReader("login.txt");
BufferedReader br = new BufferedReader(in);
String username = txtUser.getText();
String pass = txtPass.getText();
while ((record = br.readLine()) !=null) {
String[] split = record.split(",");
if (username.equals(split[0]) && pass.equals(split[1])) {
JOptionPane.showMessageDialog(null, "YOU IS LOG IN",
"OK", JOptionPane.WARNING_MESSAGE);
}
else {
JOptionPane.showMessageDialog(null, "ACCOUNT OR PASSWORD IS NOT ACCURATE",
"False", JOptionPane.WARNING_MESSAGE);
}
// Delete else branch
}
} catch (IOException e) {
e.getCause();
}
}
});
it is login.txt
user,pass
Taka,123
and txtpass is a textfiel normal
Just going out on a limb here as I cannot comment yet, but it might have to do with your inclusion of user,pass in the login.txt file. Try to remove that line so the file starts with the actual user and password.
Also, I'm not sure about the use of this code, but storing passwords in a plaintext file is never a good idea.

Hash Set giving error when comparing an input

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

How to return 1 String in case there are multiple IF statements

How can I return 1 value, in case I have some IF statements?
For example, when I choose Shopify, it calls a new method that allows me to type into console some need credentials and then append all typied data into 1 String and return that String(test) to Main class.
In case, I choose Bigcommerce, it calls pretty much the same method and append all needed credentials for Biggcomerce into 1 String(test2) as well. But in this case public String credentailsCollector() should return test2.
How can I do that? Thanks.
public class CartCredentialsCollector {
//it should return something like this:
//store_url=https://test.myshopify.com&apiKey=myapikey&apiPassword=myapipassword
public String credentailsCollector() throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Do you want to connect a new shopping cart ('yes'/'no')");
String newConnection = bufferedReader.readLine();
if (newConnection.equals("no")) {
bufferedReader.close();
} else {
System.out.println("Specify your shopping cart. It works with Shopify and Bigcommerce only");
String newShoppingCart = bufferedReader.readLine();
if (newShoppingCart.equals("Shopify")) {
ShopifyCredentialsHandler sch = new ShopifyCredentialsHandler();
String test = sch.shopifyCredentialsHandler();
}
else if (newShoppingCart.equals("Bigcommerce")) {
BigcommerceCredentialsHandler bch = new BigcommerceCredentialsHandler();
String test2 = bch.bigcommerceCredentialsHandler()
}
else {
System.out.println("This method works with Shopify and Bigcommerce. Try to connect a Shopify or Bigcommerce store.");
bufferedReader.close();
}
}
// Here I need to return test (in case I choose "Shopify") or test2 (in case I choose "Bigcommerce"). How can I do that?
}
}
You can use a method scope String variable and set the value of that instead of two different String variables. Something like this:
public class CartCredentialsCollector {
//it should return something like this:
//store_url=https://test.myshopify.com&apiKey=myapikey&apiPassword=myapipassword
public String credentailsCollector() throws IOException {
String test = null;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Do you want to connect a new shopping cart ('yes'/'no')");
String newConnection = bufferedReader.readLine();
if (newConnection.equals("no")) {
bufferedReader.close();
} else {
System.out.println("Specify your shopping cart. It works with Shopify and Bigcommerce only");
String newShoppingCart = bufferedReader.readLine();
if (newShoppingCart.equals("Shopify")) {
ShopifyCredentialsHandler sch = new ShopifyCredentialsHandler();
test = sch.shopifyCredentialsHandler();
}
else if (newShoppingCart.equals("Bigcommerce")) {
BigcommerceCredentialsHandler bch = new BigcommerceCredentialsHandler();
test = bch.bigcommerceCredentialsHandler()
}
else {
System.out.println("This method works with Shopify. Try to connect a Shopify store.");
bufferedReader.close();
}
}
return test;
// Here I need to return test (in case I choose "Shopify") or test2 (in case I choose "Bigcommerce"). How can I do that?
}
}
You should either declare test before your if statements or make multiple returns - one inside each if.
As you have realised, the reason you can't access the "test" or "test2" variables where you want to make your return is because both of them are out of scope at that point.
You need to either declare a String variable up top (before your first if statement) where the scope of the variable would extend through the entire credentialsCollector() method, or use multiple returns, putting each return in the same scope as your "test" and "test2" variables.

Java .txt username and password not working [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I was just experimenting with java (NetBeans) and I though up a quick text based adventure game. I'm trying to get it to check for your username and password in two text files "users.txt" and "passwords.txt" and i was following a guide on Cave of Programming
Here are the imports
import java.io.*;
import javax.swing.JFrame;
This is where the errors are,
private void loginActionPerformed(java.awt.event.ActionEvent evt) {
String usernametxt = "users.txt";
String passwordtxt = "passwords.txt";
String user = null;
String pass = null;
try {
// file reader for username \\
FileReader fileReader = new FileReader(usernametxt);
// file reader for password \\
FileReader fr = new FileReader(passwordtxt);
// buffered reader for username \\
BufferedReader bufferedReader = new BufferedReader(fileReader);
// buffered reader for password \\
BufferedReader br = new BufferedReader(fr);
// check for if user doesn't equal null \\
while((user = bufferedReader.readLine()) != null){
// if username equals first line of username.txt \\
if (username.getText().equalsIgnoreCase(user)){
// check for if pass doesn't equal null \\
while((pass = br.readLine()) != null){
// if password equals first line of passwords.txt \\
if (password.getPassword().equals(pass)){
// if password = pass than it will exit \\
System.exit(1);
}
// else continue \\
else{
continue;
}
}
}
}
bufferedReader.close();
br.close();
}
catch(FileNotFoundException ex){
System.out.println("Unable to open file ");
}
catch(IOException ex){
System.out.println("Error reading file");
}
}
Here are the text files
users.txt
matthew
passwords.txt
matt
Full code available here
http://textuploader.com/57urs
Newest Code Here
http://textuploader.com/577qk
feel free to ask me questions here.
Thank you for the help in advance!
Newest Code
private void loginActionPerformed(java.awt.event.ActionEvent evt) {
String usernames = username.getText();
String passwords = password.toString();
boolean signedin = false;
String usernametxt = "users.txt";
String passwordtxt = "passwords.txt";
String user = null;
String pass = null;
try {
FileReader fr1 = new FileReader(usernametxt);
FileReader fr2 = new FileReader(passwordtxt);
BufferedReader br1 = new BufferedReader(fr1);
BufferedReader br2 = new BufferedReader(fr2);
System.out.println("Username: "+br1.readLine());
System.out.println("Password: "+br2.readLine());
// While loops not running (not a if statement error \
while ((user = br1.readLine()) != null){
// checks if username is not equal to usernames.txt \\
if (user.equalsIgnoreCase(usernames)){
System.out.println("while loop running, username (right)");
break;
}
else{
System.out.println("while loop running, username (wrong)");
}
}
br1.close();
while ((pass = br2.readLine())!= null){
if (pass.equalsIgnoreCase(passwords)){
signedin = true;
System.out.println("While loop running, password (right)");
break;
}
else{
System.out.println("While loop running, password (wrong)
}
}
br2.close();
// Commented out the if statements because i dont want to to close while testing \
// if (signedin){
// System.out.println("SIGNEDIN = TRUE");
// new error1().setVisible(true);
// this.dispose();
// }
// if (!signedin){
// System.out.println("SIGNEDIN = FALSE");
// System.exit(1);
// }
}
catch(FileNotFoundException ex){
System.out.println("Unable to open file ");
}
catch(IOException ex){
System.out.println("Error reading file");
}
}
New Problem
The while loops do not run, this is confirmed when it doesn't print "While loop running, User/Pass", This is not a if/then statement error as I have added the else statement to print if the username is right or wrong. Please help, Thanks Matthew.
If i understood it correctly:
Two files:
users.txt holds the usernames.
passwords.txt holds the passwords.
We want:
Keep reading the user file until the file ends or we've found our user.
Read the corresponding line on the password file and check if the password matches.
Checking the code, while((user = bufferedReader.readLine()) != null) does the first part nicely. We DO want to keep reading the entire file trying to find our user, right?
but the nested while seems a bit fishy. We only need to check a SINGLE password for a given user, right? RIGHT?
Digging a bit deeper into your code, we see:
if (password.getPassword().equals(pass)) {
// if password = pass than it will exit
System.exit(1);
} // plus Lots of code...
Hey! I don't think System.exit does what you're looking for!
System.exit will exit the program, going back to DOS or whatever the cool kids are using these days. The integer it returns is called an error code, and can be used to feed info back to the terminal/shell that started our program.
The keyword you're most likely looking for is break: that will exit a given loop pronto, no questions asked.
Let's do some break/continue mashups! Suppose we "Win at life" if the password is indeed correct:
boolean winAtLife = false;
while((user = bufferedReader.readLine()) != null){
String candidatePassword = br.readLine();
if (candidatePassword == null) {
// So the password file is shorter than the userfile?
// We probably want to log or alert the poor DevOp guys.
// throwing an exception seems like the right thing to do here!
break;
}
if (!user.equalsIgnoreCase(username.getText())) {
// These are not the droid we're looking for, Better luck next line!
continue;
// Also notice that, since we KNOW that user can't be null,
// we're using the force to save ourselves from dreaded NullPointerExceptions!
}
if (!candidatePassword.equals(password.getPassword())) {
// Hmmm, wrong password, I guess?
// Not sure what do do next, but we DO NOT need to keep looping
// since we've found our droid/user/whatever.
// So let's break and save some EC2 Cycles.
break;
}
// If we ever reach here, we got ourselves a winner!
pass = candidatePassword
winAtLife = true;
}
EDIT: Ok... So I've heard that:
The cool kids use Scanner nowadays.
Auto-closing resources is good for our health.
Something about separation of concerns and mixing domain-code with the UI. In code samples. Whatever.
So here we go, take two, now as a method:
public boolean checkCredentials(String username, String password) throws IOException {
// these two are begging to be constants or inlined.
final String usernametxt = "users.txt";
final String passwordtxt = "passwords.txt";
if (username == null || password == null) {
// You probably don't want this in production code.
// Exceptions are your best friends when something unexpected occurs.
return false;
}
try (final Reader fileReader = new FileReader(usernametxt);
final Reader passwordReader = new FileReader(passwordtxt)) {
Scanner userScanner = new Scanner(fileReader);
Scanner passwordScanner = new Scanner(passwordReader);
while(userScanner.hasNext()) {
final String user = userScanner.next();
if (!passwordScanner.hasNext()) {
// So the password file is shorter than the userfile?
// We probably want to log or alert the poor DevOp guys.
// throwing an exception seems like the right thing to do here!
return false;
}
final String candidatePassword = passwordScanner.next();
if (!user.equalsIgnoreCase(username)) {
// This is not the droid we're looking for
// Also notice that, since we KNOW that user can't be null,
// we're using the force to save ourselves
// from dreaded NullPointerExceptions!
continue;
}
if (!candidatePassword.equals(password)) {
// Hmmm, wrong password, I guess?
// Not sure what do do next, but we DO NOT need to keep looping
// So let's return early and save some EC2 Cycles.
return false;
}
// If we ever reach here, we got ourselves a winner!
return true;
}
} // yay for autocloseable
return false;
}

Java: Try/Catch Statements: While exception is caught, repeat try statements? [duplicate]

This question already has answers here:
How do you implement a re-try-catch?
(29 answers)
Closed 4 years ago.
Is there any way to do this?
//Example function taking in first and last name and returning the last name.
public void lastNameGenerator() throws Exception{
try {
String fullName = JOptionPane.showInputDialog("Enter your full name");
String lastName = fullName.split("\\s+")[1];
catch (IOException e) {
System.out.println("Sorry, please enter your full name separated by a space.")
//Repeat try statement. ie. Ask user for a new string?
}
System.out.println(lastName);
I think I can use scanner for this instead, but I was just curious about if there was a way to repeat the try statement after catching an exception.
Something like this ?
while(condition){
try{
} catch(Exception e) { // or your specific exception
}
}
One way is to use a while loop and exit when the name has been set properly.
boolean success = false;
while (!success) {
try {
// do stuff
success = true;
} catch (IOException e) {
}
}
There is no "re-try" in the language, like others suggested already: create an outer while loop and set a flag in the "catch" block that triggers the retry (and a clear the flag after a successful try)
Would it be ok to use external lib?
If so, check out Failsafe.
First, you define a RetryPolicy that expresses when retries should be performed:
RetryPolicy retryPolicy = new RetryPolicy()
.retryOn(IOException.class)
.withMaxRetries(5)
.withMaxDuration(pollDurationSec, TimeUnit.SECONDS);
Then, you use your RetryPolicy to execute a Runnable or Callable with retries:
Failsafe.with(retryPolicy)
.onRetry((r, f) -> fixScannerIssue())
.run(() -> scannerStatement());
You can use https://github.com/bnsd55/RetryCatch
Example:
RetryCatch retryCatchSyncRunnable = new RetryCatch();
retryCatchSyncRunnable
// For infinite retry times, just remove this row
.retryCount(3)
// For retrying on all exceptions, just remove this row
.retryOn(ArithmeticException.class, IndexOutOfBoundsException.class)
.onSuccess(() -> System.out.println("Success, There is no result because this is a runnable."))
.onRetry((retryCount, e) -> System.out.println("Retry count: " + retryCount + ", Exception message: " + e.getMessage()))
.onFailure(e -> System.out.println("Failure: Exception message: " + e.getMessage()))
.run(new ExampleRunnable());
Instead of new ExampleRunnable() you can pass your own anonymous function.
You need a recursion
public void lastNameGenerator(){
try {
String fullName = JOptionPane.showInputDialog("Enter your full name");
String lastName = fullname.split("\\s+")[1];
catch (IOException e) {
System.out.println("Sorry, please enter your full name separated by a space.")
lastNameGenerator();
}
System.out.println(lastName);
}
Just put try..catch inside while loop.
Signature of showInputDialog() is
public static java.lang.String showInputDialog(java.lang.Object message)
throws java.awt.HeadlessException
and that of split() is
public java.lang.String[] split(java.lang.String regex)
None of then throw IOException. Then how are you catching it?
Anyway possible solution to your problem would be
public void lastNameGenerator(){
String fullName = null;
while((fullName = JOptionPane.showInputDialog("Enter your full name")).split("\\s+").length<2) {
}
String lastName = fullName.split("\\s+")[1];
System.out.println(lastName);
}
No need of try-catch. tried it myself. It works fine.
This sure is a simplified code fragment because in this case I'd simply remove the try/catch altogether - IOException is never thrown. You could get an IndexOutOfBoundsException, but in your example it really shouldn't be handled with exceptions.
public void lastNameGenerator(){
String[] nameParts;
do {
String fullName = JOptionPane.showInputDialog("Enter your full name");
nameParts = fullName != null ? fullName.split("\\s+") : null;
} while (nameParts!=null && nameParts.length<2);
String lastName = nameParts[1];
System.out.println(lastName);
}
EDIT: JOptionPane.showInputDialog might return null which wasn't handled before. Also fixed some typos.

Categories

Resources