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() {...}
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!
This question already has an answer here:
Closing a Scanner throws java.util.NoSuchElementException
(1 answer)
Closed 4 years ago.
Currently im new to java, and im trying to get my code to restart from the top so essentially you can keep entering sentences until user cancels on purpose. Currently i keep getting an error.
import java.util.Scanner;
public class Reverser {
public static void main(String[] args) {
boolean run = true;
while(run) {
for(;;) {
Scanner scan = new Scanner(System.in);
System.out.println("Hello Welcome To The Sentence Reverser !");
System.out.println("Enter a sentence below to reverse.");
String str = scan.nextLine();
scan.close();
String reversedStr = new StringBuilder(str).reverse().toString();
System.out.println("Initial Sentence: " + str);
System.out.println("Reversed Sentence: " + reversedStr);
}
}
}
}
I once did something similar to this, this was for moderators to check specific user accounts. You basically re-call the search method after input handling. This way you can reset the program to a previous state.
/**
* #author Stan van der Bend
*/
public class Scanner {
private static final String CHARACTER_FILE_PATH = "data/characters";
private static ArrayDeque<String> matches = new ArrayDeque<>(200);
public static void main(final String... args) throws IOException {
search();
}
private static void search() throws IOException{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your desired keyword: ");
String keyword = reader.readLine();
System.out.println("Started scanning all files...");
long start = System.currentTimeMillis();
try {
Path path = Paths.get(CHARACTER_FILE_PATH);
Files.walkFileTree(path, new SimpleFileVisitor<>() {
#Override
public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
matches.addAll(Files
.readAllLines(path)
.stream()
.filter(line -> line.contains(keyword))
.collect(Collectors.toList())
);
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
e.printStackTrace();
System.out.println("Make sure this is in the same directory as "+CHARACTER_FILE_PATH);
}
long duration = System.currentTimeMillis() - start;
System.out.println("Found "+matches.size()+" matches for the keyword "+keyword);
matches.stream().sorted(Comparator.comparing(PlayerLogs::getDate)).forEach(System.out::println);
System.out.println("The scan toke " + duration + "ms to complete.");
System.out.print("For another scan type -r ");
matches.clear();
if(reader.readLine().equalsIgnoreCase("-r"))
search();
reader.close();
}
}
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
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();