In my GUI.java class, I have the following function:
public void setChat(String text)
{
chat.append(text);
}
public void getInput(String text)
{
String read = input.getText();
}
I am trying to use my getInput() method to set a username I will be using for the rest of my code, but I just can't seem to read it in correctly from the TextField in my Client.java. I'm having a lot of trouble getting the original:
String username = gui.getInput();
(That certainly didn't work either). Can someone help me read in a TextField entry and assign it to my username String?
import java.io.*;
import java.net.*;
public class Client
{
public static void main(String [] args) throws IOException
{
GUI gui = new GUI();
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
//GUI gui = new GUI();
}
});
String username = "";
gui.setChat(" Enter the username you would like to use for the duration of the chat session.\n");
if (username == "")
{
System.out.println("Press Any Key To Continue...");
new java.util.Scanner(System.in).nextLine();
gui.getInput(username);
gui.setChat(" Your username is now: " + username + ".\n");
}
}
}
EDIT 1
GUI.java class:
String getInput(String text)
{
return input.getText();
}
Client.java class:
String username;
gui.setChat(" Enter the username you would like to use for the duration of the chat session.\n");
username = gui.getInput();
System.out.println("Press Any Key To Continue...");
new java.util.Scanner(System.in).nextLine();
gui.setChat(" Your username is now: " + username + ".\n");
Errors:
Client.java:19: error: method getInput in class GUI cannot be applied to given types;
username = gui.getInput();
^
required: String
found: no arguments
reason: actual and formal argument lists differ in length
1 error
try
public void getInput(){
return input.getText();
}
then in the main
username = "" + gui.getInput();
Related
you may have seen my previous question, this builds on that with the implementation of a handler. however im finding it difficult to get it to work correctly.
i have three classes:
main.java
- simple method which requests to read console and then outputs the user input.
handler.java
- requests 'readconsole' from gui.java
gui.java
- displays gui
- reads console
feel like im missing something simple!
main.java
public class main {
static handler handler = new handler();
public static void main(String[] args) {
}
public static void menuSwitch(String input) {
System.out.println("entered menu switch with input " +input);
String s = handler.requestReadConsole();
System.out.println(s);
}
}
handler.java
public class handler {
static gui gui = new gui();
static String inputvariable= null;
public handler() {
requestAndSortReadConsole();
}
public String requestReadConsole() {
System.out.println("entered read console");
String s = gui.readConsole();
return s;
}
public String requestAndSortReadConsole() {
System.out.println("entered requestAndSortReadConsole");
sortInput(requestReadConsole());
System.out.println("sorted value = " + inputvariable);
return inputvariable;
}
public void sortInput(String input) {
System.out.println("entered sort input with input = " + input);
if (input.length() == 1) {
System.out.println("input length EQUALS 1");
main.menuSwitch(input);
}else {
inputvariable = input;
System.out.println(inputvariable);
}
System.out.println("return input");
}
}
gui.java
public class gui {
static Scanner in = new Scanner(System.in);
public gui() {
System.out.println("main menu called");
mainMenu();
}
public void mainMenu() {
System.out.println("press 1 for case 1");
System.out.println("press 2 for case 2");
System.out.println("press 3 for case 3");
}
public String readConsole () {
String input = null;
System.out.println("entered readconsole gui");
input = in.nextLine();
System.out.println("input = " + input);
in.close();
return input;
}
}
The method menuSwitch should print variable s but it doesnt print anything and continues to allow user to input to console!
I have implemented a basic login system that splits up a text file (first name : last name : City : username : password)
Harold : Fisher : San Francisco : hf45 : 1234
When the user inputs his/her user credentials, it will display a JFrame if credentials are entered correctly, otherwise a JOptionPane will appear instead informing the user that the credentials entered are incorrect.
Here is my code:
public class LoginFrame extends javax.swing.JFrame {
/**
* Creates new form LoginFrame
*/
String username;
String password;
String filePath = "UserDetails.txt";
public LoginFrame() {
initComponents();
private void jButtonLoginActionPerformed(java.awt.event.ActionEvent evt) {
username = jTextFieldUsername.getText();
password = jTextFieldPassword.getText();
verifyLogin();
}
public void verifyLogin()
{
try {
File f = new File("UserDetails.txt");
Scanner fileRead = new Scanner(f);
while(fileRead.hasNextLine())
{
String textLine = fileRead.nextLine();
String[] userDetails = textLine.split(" : ");
String tempUsername = userDetails[3];
String tempPassword = userDetails[4];
if(tempUsername.trim().equals(username.trim()) && tempPassword.trim().equals(password.trim()))
{
new LibraryCatalogFrame().setVisible(true);
}
else
{
JOptionPanes.messageBox("Please re-enter your user details", "Incorrect Username or Password");
}
}
}
catch (FileNotFoundException e)
{
JOptionPanes.messageBox("Error", "FileNotFound");
}
}
The problem I am facing right now is that when the user correctly inputs his credentials, both the JFrame and JOptionPane are displayed. Also, when the user inputs his credentials incorrectly, the JFrame does not display (as intended), but the JOptionPane appears twice instead of just once.
I observed the behavior you explain when UserDetails.txt file has two lines. E.g.
Harold : Fisher : San Francisco : hf45 : 1234
John : Snow : San Francisco : js45 : 5678
With above file with 2 lines, below "Program with the problem" outputs the behavior you explain (both "Show JFrame" and "Show dialog" are printed).
Problem is that, in the while loop, you try to show JFrame or dialog for every line in the file.
Try below "Fixed program". In that, I'm using a boolean variable matched to store whether a match is found. And then show the JFrame or dialog after the while loop.
Program with the problem:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class LoginFrame
{
// Hardcode user entered username and password to simplify the program
String username = "hf45";
String password = "1234";
public static void main(String[] args)
{
new LoginFrame().verifyLogin();
}
public void verifyLogin()
{
try {
File f = new File("UserDetails.txt");
Scanner fileRead = new Scanner(f);
while(fileRead.hasNextLine())
{
String textLine = fileRead.nextLine();
String[] userDetails = textLine.split(" : ");
String tempUsername = userDetails[3];
String tempPassword = userDetails[4];
if(tempUsername.trim().equals(username.trim()) && tempPassword.trim().equals(password.trim()))
{
//new LibraryCatalogFrame().setVisible(true);
System.out.println("Show JFrame");
}
else
{
System.out.println("Show dialog");
//JOptionPanes.messageBox("Please re-enter your user details", "Incorrect Username or Password");
}
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
//JOptionPanes.messageBox("Error", "FileNotFound");
}
}
}
Output:
Show JFrame
Show dialog
Fixed program:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class LoginFrame
{
// Hardcode user entered username and password to simplify the program
String username = "hf45";
String password = "1234";
public static void main(String[] args)
{
new LoginFrame().verifyLogin();
}
public void verifyLogin()
{
try {
File f = new File("UserDetails.txt");
Scanner fileRead = new Scanner(f);
boolean matched = false;
while(fileRead.hasNextLine())
{
String textLine = fileRead.nextLine();
String[] userDetails = textLine.split(" : ");
String tempUsername = userDetails[3];
String tempPassword = userDetails[4];
if(tempUsername.trim().equals(username.trim()) && tempPassword.trim().equals(password.trim()))
{
matched = true;
break;
}
}
if (matched)
{
//new LibraryCatalogFrame().setVisible(true);
System.out.println("Show JFrame");
}
else
{
System.out.println("Show dialog");
//JOptionPanes.messageBox("Please re-enter your user details", "Incorrect Username or Password");
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
//JOptionPanes.messageBox("Error", "FileNotFound");
}
}
}
We worked progressively on a project. Last milestone is dividing this into the following: Create a class with four methods: main method, a method for creating customer information(void), a method for creating user name and password (void) and finally a method for log-in(return type).
I have implemented the log-in method, when moving to implementation of the loginDetails, I ran into problems. I don't understand how I can create loginDetails in a void method, and also be able to check against it in a different method. My loginDetail method is not returning a value to main, and my variables are local for the methods.
How can I create the user details in a void method, and be able to create the login check in a separate method?
This is my code, I would like to use the details generated in loginDetails(); as the values to check against instead of the manually inserted strings.
public class Customer {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
loginDetails("testtest", "testtest", "11111121111");
System.out.print(logIn("ABC", "212"));
}
public static void customerInformation() {
//Create customerInformation
}
public static void loginDetails(String firstName, String lastName, String number) {
String userName, password;
userName = firstName.charAt(0) + lastName.substring(0, 3);
password = lastName.substring(0, 3) + number.substring(7);
}
public static String logIn(String userName, String password) {
int count = 0;
while (count < 3) {
System.out.print("Input Username");
String inputUserName = input.nextLine();
System.out.print("Input password");
String inputPassword = input.nextLine();
if (inputUserName.equals(userName) && inputPassword.equals(password)) {
return "You are now logged in";
} else {
count++;
if (count < 3)
System.out.println("Wrong Username or password. Try again");
}
} //While
return "Try again in a few hours"; //Third try
} //logIn
}
class Customer {
static Scanner input = new Scanner(System.in);
static String userName=null;
static String password=null;
public static void main(String[] args) {
loginDetails("testtest", "testtest", "11111121111");
System.out.print(logIn("ABC", "212"));
}
public static void customerInformation() {
//Create customerInformation
}
public static void loginDetails(String firstName, String lastName, String number) {
userName = firstName.charAt(0) + lastName.substring(0, 3);
password = lastName.substring(0, 3) + number.substring(7);
}
public static String logIn(String userName, String password) {
int count = 0;
while (count < 3) {
System.out.print("Input Username");
String inputUserName = input.nextLine();
System.out.print("Input password");
String inputPassword = input.nextLine();
if (inputUserName.equals(userName) && inputPassword.equals(password)) {
return "You are now logged in";
} else {
count++;
if (count < 3)
System.out.println("Wrong Username or password. Try again");
}
} //While
return "Try again in a few hours"; //Third try
} //logIn
}
I am creating a simple login program in java. Here is the code i have so far.
import java.util.Scanner;
import java.io.*;
import java.util.Arrays;
public class PasswordProgram {
public static String user;
public String password;
public static boolean part1Finish = false;
public File file = new File("D:/file.txt");
public FileWriter UsernameWrite;
public char[] user1;
public void part1() {
System.out.println("Please create an account: ");
Scanner input = new Scanner(System. in );
System.out.println("Type in a username: ");
String user = input.next();
System.out.println("Type in a Password: ");
String password = input.next();
try {
UsernameWrite = new FileWriter(file);
UsernameWrite.write(user);
UsernameWrite.write(password);
System.out.println(user);
UsernameWrite.close();
part1Finish = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void part2() {
Scanner scan = new Scanner(System. in );
System.out.println("Please confirm your username: ");
String usercheck = scan.next();
int PassAttempts = 5;
int UserAttempts = 5;
user1 = user.toCharArray();
user1 = password.toCharArray();
char[] usernamecheck = java.util.Arrays.copyOfRange(user1, 0, user.length());
System.out.println(usernamecheck);
do {
if (usercheck.equals(usernamecheck)) {
while (PassAttempts > 0) {
System.out.println("Please confirm your password: ");
String passcheck = scan.next();
if (passcheck.equals(password)) {
System.out.println("Thank You ");
} else if (passcheck != password && PassAttempts > 0) {
PassAttempts--;
System.out.println("That is incorrect. Please Try Again");
passcheck = scan.nextLine();
} else {
System.out.println("You have run out of Password Attempts");
break;
}
}
} else if (usercheck != user && UserAttempts > 0) {
UserAttempts--;
System.out.println("That is an incorrect username. Please Try Again");
usercheck = scan.nextLine();
} else {
System.out.println("You have run out of Username Attempts");
break;
}
} while (UserAttempts > 0);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
PasswordProgram login = new PasswordProgram();
login.part1();
if (part1Finish == true) {
login.part2();
}
}
}
The problem i am getting is in the method part2. Here when I try to add the username that was saved under the variable user into a character array to use it as a range I get the error NullPointerException.
After investigating i see that when running part2 the value of user is null and therefore I get the error.
Is there a way I could do this through the FileReader method instead or how can i fix the current error I am getting ? Thank you.
Because the static field user is never assigned in part1, you get a NullPointerException when you try to use it in part2.
There are also other issues in the posted code:
why there is a file involved is unclear
you use != with String, for example in passcheck != password
you use equals between String and char[] in usercheck.equals(usernamecheck)
passcheck is assagned but never used
local variables (because of their names) are hiding some fields
UsernameWrite and UserAttempts have non conventional names (should be usernameWrite and userAttempts
You have two user variables declared, one which is static and has global scope, another which is local to part1(). When part2() is attempting to access user, it is using the static declaration, which is null. Your modifications to user in part1() are done to the local variable.
This is something called variable shadowing and should be avoided at all costs.
See the below example:
class Ideone
{
static String bla = "test1";
public static void myMethod() {
String bla = "test2";
System.out.println(bla);
}
public static void main (String[] args) throws java.lang.Exception
{
myMethod();
System.out.println(bla);
}
}
It outputs:
test2
test1
I'm getting an error that
"Illegal start of expression and error ';' expected"
I don't know if I'm doing the new method right, so please help me I need this for school work.
public class Testing{
public static void main(String args[])throws IOException{
String un, pw, login;
final String Username = "javajava";
final String Password = "testing";
BufferedReader inpt = new BufferedReader (new InputStreamReader(System.in));
public void Login(){
System.out.println("Please enter your Username & Password for you to be able to use the program");
System.out.println("Warning! Case Sensitive!");
for(int trial=3; trial>=1; trial--){
System.out.print("Username: ");
un = inpt.readLine();
System.out.print("Password: ");
pw = inpt.readLine();
System.out.println();
if(un.equals(Username) && pw.equals(Password)){
System.out.println("User has successfully logged in!");
break;
} else {
System.out.println("Sorry, you've entered an incorrect Username/Password - (" + (trial-1) + ") retries left");
}
if (trial==1){
System.out.println("It seems that you've reached the limit for the login attempts, please try again later");
}
}
}
You can't[1] have a method inside a method.
Move
public void Login(){
To outside
public static void main(String args[])throws IOException{.
I advise you to go through the tutorial Defining Methods.
[1] You can, indirectly, have a "method inside a method". It is possible to have a method that contains an inner class, and that class will contain a method. So.. you actually get a method inside a method ;)
try
import java.io.*;
public class Testing {
static String un, pw, login;
static final String Username = "javajava";
static final String Password = "testing";
public static void Login() throws IOException {
System.out
.println("Please enter your Username & Password for you to be able to use the program");
System.out.println("Warning! Case Sensitive!");
BufferedReader inpt = new BufferedReader(new InputStreamReader(
System.in));
for (int trial = 3; trial >= 1; trial--) {
System.out.print("Username: ");
un = inpt.readLine();
System.out.print("Password: ");
pw = inpt.readLine();
System.out.println();
if (un.equals(Username) && pw.equals(Password)) {
System.out.println("User has successfully logged in!");
break;
} else {
System.out
.println("Sorry, you've entered an incorrect Username/Password - ("
+ (trial - 1) + ") retries left");
}
if (trial == 1) {
System.out
.println("It seems that you've reached the limit for the login attempts, please try again later");
}
}
}
public static void main(String args[]) throws IOException {
Login();
}
}
You need to declare your method outside your main method:
public static void main(String[] args) {...}
public static void Login() {...}