Java help JOptionPane Madness - java

Really needing help on this have been trying for the past hour playing around and can't seem to get it. Have looked for the question online and getting a lot of solutions that are similar but not quite accomplishing the task would appreciate if someone could help me with this?
I am currently working on a dropBox API and am trying to create a JOptionPane that prompts the user to enter the code generated from dropBox API and the program to read the input and verify.. I have done the System.in with success but this is for a GUI so obviously not helpful.
System.out.println("Enter Your auth code in this prompt and hit enter and wait..");
String result = JOptionPane.showInputDialog(null, "Enter Code Here: ");
String code = new BufferedReader(new InputStreamReader(System.in)).readLine();
// Want JOptionPane to function the same way this ^ would behave
String info = JOptionPane.showInputDialog(code +" test " );
if(code == null){
System.exit(1);
return;
}
code = code.trim();
// This will fail if the user enters an invalid authorization code.
DbxAuthFinish authFinish = webAuth.finish(code);
String accessToken = authFinish.accessToken;
DbxClient client = new DbxClient(config, accessToken);
System.out.println("Linked account: " + client.getAccountInfo().displayName);
JOptionPane.showMessageDialog(null, "Hello..."+
client.getAccountInfo().displayName+
" And Welcome To Our Community!");

The String 'result' should hold the code they entered into the JOptionPane.
EDIT #1:
String result = JOptionPane.showInputDialog(null, "Enter your auth code here:"); //Prompt for the auth code.
//If they didn't enter anything into the JOptionPane then close the program with code 1.
if (result.isEmpty()) {
System.exit(1);
}
System.out.println(result.trim()); //For testing purposes print the trimmed auth code to console.
// [Omitted Code] //
Also, you don't need to call return after a System.exit(#) because the program will never get to that code anyway.

Related

Password Masking in Java with Scanner

I'm a high school student learning Java and I want to know how to change input text automatically into an asterisk in Scanner. This is for a simple log-in system I have made for a project. My code is
Scanner scan = new Scanner(System.in);
boolean correctLogin = false;
String username;
String password;
String enteredUsername;
String enteredPassword;
while(correctLogin != true){
System.out.println("Enter Username: ");
enteredUsername = scan.nextLine();
System.out.println("Enter Password: ");
enteredPassword = scan.nextLine();
if(enteredUsername.equals("username") && enteredPassword.equals("passw00rd")){
System.out.println("You have entered the correct login info");
correctLogin = true;
break;
}
else{
System.out.println("Your login info was incorrect, please try again");
}
}
System.out.println("You are now logged in, good job!");
I want it so that when I type the password, it will automatically change into an asterisk.
try with this for password read:
Console console = System.console();
if(console != null){
console.readPassword("Enter Password: ");
}
I also had the same issue with my console java application and
I also do not want to display password in my IDE for security reasons.
So, to find the bug I had to debug against the productive environment. Here is my solution that works for me in IntelliJ IDEA:
public static String getPassword() {
String password;
Console console = System.console();
if (console == null) {
password = getPasswordWithoutConsole("Enter password: ");
} else {
password = String.valueOf(console.readPassword("Enter password: "));
}
return password;
}
public static String getPasswordWithoutConsole(String prompt) {
final JPasswordField passwordField = new JPasswordField();
return JOptionPane.showConfirmDialog(
null,
passwordField,
prompt,
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE) == JOptionPane.OK_OPTION ? new String(passwordField.getPassword()) : "";
}
I am not sure if i get your question correctly, but still I will try to explain of what I understood.
To ensure that you see *** on the user screen you need to have some kind of a User interface written in HTML. I think in this case you are running your code in eclipse and via some kind of a main method. If that is the case then as Vince mentioned there is no benefit of ** since the letters would appear in the console.
What I would recommend is look for something basic web application tutorial and you would have more idea on how it works then.
HTH

ArrayIndexOutOfBoundsException when checking an array?

I've been making a instant chat program, and wanted to make it possible for users to "whisper" or private message one another. The way I implemented that is the user would type:
/w [username] [message]
I then send it to the server which sends it to all the users. The users then have to check to see if its sent to them, this is that method:
if (message.startsWith("/msg/")) {
message = message.trim();
message = message.substring(5);
String[] words = message.split("//s");
String UserName = null;
try {
String username = words[2];
UserName = username;
System.out.println(UserName);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error reading the whisper command!");
}
if (UserName == client.getName()) {
List<String> list = new ArrayList<String>(Arrays.asList(words));
list.removeAll(Arrays.asList(2));
words = list.toArray(words);
String text = words.toString();
text = "You've been whispered! " + message;
console(text);
}
Everytime I send a /w when I'm testing it always give the ArrayIndexOutOfBoundsException. I also modify the message in the sending. Heres that method:
else if (message.toLowerCase().startsWith("/w")) {
message = "/msg/" + client.getName() + message;
message = "/m/" + message + "/e/";
txtMessage.setText("");
}
I also added a whole bunch more options for the actual code for the users, I made it /whisper, /m, /msg, and /message, but those are all just copies of this with a different input. Why is it giving me an ArrayIndextOutOfBoundsException, when the 3rd place in the words array SHOULD be the username that the sender is trying to send it to. Obviously this probably isn't the best way to send private messages, and if any of you guys have a simpler way I can implement to my server, please go ahead and let me know! Just know that I am a young, new programmer and so I will probably have a lot of questions.
The slashes in your split() regex are backwards. You need
String[] words = message.split("\\s");
You can also just use a space
String[] words = message.split(" ");

read a file and determine a String

assume that my text file consist this:
NOT VOTED/1/gello/18
NOT VOTED/2/tara/24
arrangements is like status if user already voted or not/voter's number/name/age i divided the information line into array so it is like this
info[0]=status/info[1]=voters number/info[2]=name/info[3]=age
here is the function of my program:
read a file
let the user enter a voters number
if voters number matches info[1], proceed to step 3
while info[0] contains "VOTED" it will get an error message that that voter's number already voted and enter another voters number. if false it will proceed to the voting process
now info[0] will changed in to "VOTED"
here is my code:
File original = new File("C:\\voters.txt");//open the original file
File temporary = new File("C:\\tempvoters.txt");//create temporary file
BufferedReader infile = new BufferedReader(new FileReader(original));//read the file
PrintWriter outfile = new PrintWriter(new PrintWriter(temporary));//write the data
vNum=JOptionPane.showInputDialog("Enter voters number: ");
String line=null;
String something="VOTED";
while((line=infile.readLine())!=null){
String [] info=line.split("/");
if(info[1].matches(vNum)){
while(info[0].matches(something)) {
JOptionPane.showMessageDialog(null, "Voter already voted or Voter not registered. Please try again");
vNum=JOptionPane.showInputDialog("Enter voters number: ");
}
President();
Vice_President();
info[0]="VOTED";
all=info[0]+"/"+info[1]+"/"+info[2]+"/"+info[3]+"/"+info[4]+"/"+info[5]+"/"+info[6]+"/"+info[7]+"/"+info[8]+"/"+info[9]+"/"+info[10]+"/"+info[11]+"/"+info[12];
outfile.println(all);
outfile.flush();
}
else{
outfile.println(line);
outfile.flush();
}
}
infile.close();
outfile.close();
original.delete();//delete the original file
temporary.renameTo(original);//rename the temporary file to original file
now this happens in the code that i made:
assume i enter 1 as voters number. and because the info[0] still contains "NOT VOTED", it will proceed to voting process and after that the element of info[0] now contains "VOTED". now after that process it will go back to main menu. now when i go back entering another voters number again, i tried entering 1 again to see if it will appear the error message. it did. so i entered the other voter's number again which is 2 and its info[0] still contains "NOT VOTED" BUT the error message will still appear!! i am really stuck with that process and i don't know what to do with that anymore because i am really clueless what is wrong. to think the functions in this method of my program are just the same with the other methods that i had. please please please help
while(info[0].matches(something))
It looks to me as though you're not breaking out of this while loop, since info[0] will always be true since variable "something" isn't being changed. What I would suggest is this:
{
JOptionPane.showMessageDialog(null, "Voter already voted or Voter not registered. Please try again");
vNum=JOptionPane.showInputDialog("Enter voters number: ");
something = "NOT VOTED"; //This will break the loop
}

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

Banning users by reading variable via Java

I am creating a basic password based login system. It uses MD5 to secure the password. The correct password is "csk" (without quotes). If anyone enters that correctly, he gets access to a key.html file in the local computer. But if someone enters the wrong password for three consecutive times, he gets "banned" from logging in again. But the design that I have constructed bans the user only for that particular session. If he opens the terminal again, it starts from the very beginning. If the variable count is greater than 3 (three) from the last time, then the program, on execution via void main() would display "You are banned". I want to keep it basic and not use JDBC and SQL and such. Also, this is a local application and not a web-based one. I'm quite confused what approach I should take on this. Here's my code that I've cooked up:
import java.math.*;
import java.security.*;
import java.io.*;
import java.util.*;
import java.net.HttpURLConnection;
public class pwd {
public static void main(String[] args)throws NoSuchAlgorithmException, IOException, InterruptedException {
int count = 1;
boolean run = true;
while (run && count<4){
System.out.println("Enter the password");
Scanner kb = new Scanner(System.in);
String pass = kb.nextLine();
String pd = "ea0882721f7f44384ce772375696f9a6"; //Password is "csk" without quotes geeks, this is it's MD5
// so enter "csk" in the terminal
// to run the program on execution
String md5sum = md5(pass);
String os = System.getProperty("os.name");
boolean o = false;
int win = os.indexOf("Windows");
if (md5sum.equals(pd)){
System.out.println("You've logged in successfully, get the Key now");
String url = "file:///C:/Users/<username>/Desktop/key.html"; // example www
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
run = false;
}
else {
System.out.println("You've entered the wrong password, try again.");
System.out.println();
run = true;
if (count>=3) {
System.out.println("You are banned from logging in, due to repeated unsuccessful login attempts.");
}
++count;
}
}
}
public static String md5(String input)throws NoSuchAlgorithmException, IOException {
String md5 = null;
MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(input.getBytes(), 0, input.length());
md5 = new BigInteger(1, digest.digest()).toString(16);
return md5;
}
}
EDIT: There's no need for me to change MD5 hashing to anything else, it's just a basic one.
you can simply write to a file with java.io.FileWriter
FileWriter writer = null;
String text = "username";
try{
writer = new FileWriter("banned.txt", true);
writer.write("\r\n");
writer.write(text,0,text.length());
}catch(IOException ex){
ex.printStackTrace();
}finally{
if(writer != null){
writer.close();
}
}
The above code allows you to add a line in a file.
To read the file, you can do like this (java.io.BufferedReader):
BufferedReader reader = new BufferedReader(new FileReader("banned.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
// check the username here
}
Hum what you want to do can be done but you have to create a kind of "login page" because as it is now (with the code you gave) there is no user information involved.
To save the important information of the ban, you can for example save a boolean in a file (or the user when you have it) and read this same file at the beginning of your code in order to know if user is ban or not. In this case you have to change your code to add the information of ban or not before trying the new input codes ;)
If you don't have a login page, so no user once you ban someone no one will be able to log any more :)
PS: Java class start with a Upper case not pwd but Pwd normally
PS2: Your count will always be increased because it's not in a else ;) so every try of new code will increase it even if the user is ban ;)

Categories

Resources