I have recently started working on this program, and I'm new to inter-thread communications such as wait and notify. However when I run this, the notify doesn't seem to execute correctly. Here is the code: (sorry about the extra stuff)
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws InterruptedException {
Main console = new Main();
console.restart();
}
public void restart() throws InterruptedException {
Scanner restartinput = new Scanner(System.in);
System.out.println("System has been restarted");
System.out.println("Restarting requires an admin restart password.");
System.out.println("You may also login as a normal user to reboot but will cause that account to be temporarily locked.");
System.out.println("Enter 1 for normal user, 2 for admin");
String input12 = restartinput.nextLine();
boolean lockall = false;
if (input12.equals("1")) {
System.out.println("Enter username:");
String input13 = restartinput.nextLine();
if (input13.equals("normalusertest")) {
boolean passwordgotten2 = false;
while (passwordgotten2 == false) {
// Not perfect hash function, some Strings and numbers have the same hash.
int realhashedpassword2 = 1544190;
System.out.println("PIN:");
Scanner input = new Scanner(System.in);
String enteredpassword2 = input.nextLine();
String plaintextguess2 = new String(enteredpassword2);
if (plaintextguess2.hashCode() == realhashedpassword2) {
System.out.println("Access granted.");
passwordgotten2 = true;
} else if (plaintextguess2.equals("/override")) {
System.out.println("Admin override password:");
String overridepasswordguess2 = input.nextLine();
if (overridepasswordguess2.hashCode() == 843331265) {
System.out.println("Access granted.");
passwordgotten2 = true;
} else {
System.out.println("Access denied.");
System.exit(0);
}
} else {
System.out.println("Access denied. Incorrect password");
}
}
for (int w = 0; w <= 45; w++) {
System.out.println(".");
}
fulllogin(0, 1);
} else {
System.out.println("That is not a normal username");
}
}
if (input12.equals("2")) {
boolean gottenpassword3 = false;
while (gottenpassword3 == false) {
System.out.println("Enter the restart password:");
String input8 = restartinput.nextLine();
if (input8.hashCode() == 48818447) {
System.out.println("Access granted.");
System.out.println("Restarting.");
for (int j = 0; j <= 45; j++) {
System.out.println(".");
}
gottenpassword3 = true;
}
}
fulllogin(0, 0);
}
}
public void fulllogin(int lockall, int locknormalusertest) throws InterruptedException {
int lockall1 = lockall;
int locknormalusertest1 = locknormalusertest;
Scanner usernameScanner = new Scanner(System.in);
System.out.println("Username:");
String inputtedusername = usernameScanner.nextLine();
String username = login(inputtedusername, lockall1, locknormalusertest1);
int currentadministrativelevel = 0;
if (username.equals("admintest")) {
currentadministrativelevel = 2;
}
if (username.equals("normalusertest")) {
currentadministrativelevel = 1;
}
runCommands(username, currentadministrativelevel, lockall, locknormalusertest);
}
public void runCommands(String username, int administrativelevel, int lockall, int locknormalusertest) throws InterruptedException {
int currentadministrativelevel = administrativelevel;
System.out.println("Command:");
Scanner commandinput = new Scanner(System.in);
String input2 = commandinput.nextLine();
if (input2.equals("/manage")) {
if (currentadministrativelevel == 2) {
System.out.println("1 user to manage");
System.out.println("Enter 1 to manage normalusertest");
if (commandinput.nextLine().equals("1")) {
System.out.println("1 to view data, 2 to manage password, 3 to lock/unlock user");
String input1 = commandinput.nextLine();
if (input1.equals("1")) {
System.out.println("No data to view currently");
}
if (input1.equals("2")) {
System.out.println(
"To log in to this account use '/override' as the password. The admin override password is the square of the password for this account.");
}
if (input1.equals("3")) {
System.out.println("'/lock' or '/unlock'");
System.out.println("Command:");
String input10 = commandinput.nextLine();
if (input10.equals("/lock")) {
System.out.println("Reenter password to confirm lock:");
System.out.println("Reenter PIN:");
String input9 = commandinput.nextLine();
if (input9.hashCode() == 1662305) {
System.out.println("Locking normalusertest.");
for (int o = 0; o <= 45; o++) {
System.out.println(".");
}
fulllogin(lockall, 1);
}
}
if (input10.equals("/unlock")) {
System.out.println("Reenter password to confirm unlock:");
System.out.println("Reenter PIN:");
String input11 = commandinput.nextLine();
if (input11.hashCode() == 1662305) {
System.out.println("Unlocking normalusertest.");
for (int p = 0; p <= 45; p++) {
System.out.println(".");
}
fulllogin(lockall, 0);
}
}
}
}
}
if (currentadministrativelevel == 1) {
System.out.println("No users to manage.");
}
}
if (input2.equals("/chat")) {
System.out.println("'/view' or '/send'");
String input14 = commandinput.nextLine();
if (input14.equals("/send")) {
System.out.println("Enter a user to send a message to. Capitalization matters.");
String input15currenttouser = commandinput.nextLine();
System.out.println("Message:");
String input16currentmessage = commandinput.nextLine();
try {
sendMessage(username, input15currenttouser, input16currentmessage, lockall, locknormalusertest);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (input14.equals("/view")) {
synchronized (this) {
boolean viewed = true;
notifyAll();
Thread.sleep(15000);
}
}
}
if (input2.equals("/logout")) {
System.out.println("Logging out.");
;
for (int i = 0; i <= 45; i++) {
System.out.println(".");
}
fulllogin(lockall, locknormalusertest);
} else {
runCommands(username, currentadministrativelevel, lockall, locknormalusertest);
}
}
public String login(String username, int lockall, int locknormalusertest) throws InterruptedException {
if (username.equals("normalusertest") && (lockall == 1 || locknormalusertest == 1)) {
System.out.println("This account has been temporarily locked.");
fulllogin(lockall, locknormalusertest);
}
if (username.equals("normalusertest") && lockall == 0 && locknormalusertest == 0) {
boolean passwordgotten = false;
while (passwordgotten == false) {
// Not perfect hash function, some Strings and numbers have the same hash.
int realhashedpassword = 1544190;
System.out.println("PIN:");
Scanner input = new Scanner(System.in);
String enteredpassword = input.nextLine();
String plaintextguess = new String(enteredpassword);
if (plaintextguess.hashCode() == realhashedpassword) {
System.out.println("Access granted.");
passwordgotten = true;
} else if (plaintextguess.equals("/override")) {
System.out.println("Admin override password:");
String overridepasswordguess = input.nextLine();
if (overridepasswordguess.hashCode() == 843331265) {
System.out.println("Access granted.");
passwordgotten = true;
} else {
System.out.println("Access denied.");
System.exit(0);
}
} else {
System.out.println("Access denied. Incorrect password");
}
}
return "normalusertest";
}
if (username.equals("admintest")) {
boolean passwordgotten = false;
while (passwordgotten == false) {
// Not perfect hash function, some Strings and numbers have the same hash.
int realhashedpassword = 1662305;
System.out.println("PIN:");
Scanner input = new Scanner(System.in);
String enteredpassword = input.nextLine();
String plaintextguess = new String(enteredpassword);
if (plaintextguess.hashCode() == realhashedpassword) {
System.out.println("Access granted.");
passwordgotten = true;
} else {
System.out.println("Access denied. Incorrect password");
}
}
return "admintest";
} else {
System.out.println("Invalid username");
return "error";
}
}
public void sendMessage(String fromuser, String touser, String message, int lockall, int locknormalusertest) throws InterruptedException {
synchronized (this) {
fulllogin(lockall, locknormalusertest);
boolean viewed = false;
while (viewed == false) {
wait();
}
System.out.println("notify test");
}
}
}
After /view is typed, the program just waits and then has "Command:" again, even though it should be printing "notify test".
I didn't grasp the whole concept of the application, but two issues seem apparent:
You're not starting any threads, therefore, there won't be any
inter-thread communications, because the only thread you'll have is
Main. Running your application on multiple threads could be
achieved, for example, by having Main extend Thread, creating
multiple instances in your static main method, and calling
start() on each. (This is just a technical example that most
likely wouldn't be appropriate for your needs, as you wouldn't want
to start printing to the console from multiple threads.)
The following synchronized blocks are trying to communicate via a
boolean viewed, but since they're each creating it as their own
local variable, they never get to each other:
synchronized (this) {
fulllogin(lockall, locknormalusertest);
boolean viewed = false;
while (viewed == false) {
wait();
}
System.out.println("notify test");
}
// ...
synchronized (this) {
boolean viewed = true;
notifyAll();
Thread.sleep(15000);
}
Threads need to communicate via data that's scoped appropriately to be
accessible to all of them. For example, if you create the threads as in my
example in #1, you can create a static field on Main and all
instances will have access to that.
public class Main {
// The 'static' keyword makes this variable available to all Main instances
private static boolean viewed = false;
// ...
I'd suggest that you read up on Java scopes and dig into this excellent resource to get a better grasp on the concepts of multithreading: http://tutorials.jenkov.com/java-concurrency/index.html
Related
In my program, I have a FacebookUser class that has an ArrayList of all of that user's friends. All of those friends may also have friends. I am using recursion to get a new ArrayList that contains all of the user's friends and all of the user's friends' friends and so on. I also serialized the FacebookUser class so I can save the data. Without the new recursive method, I can serialize without error and the data persists over executions. With the recursive method, though, I get an InvalidClassException. It shows that the exception is at the line that uses the ObjectInputStream to get the FacebookUser from memory.
I'm not understanding why the new method is causing the exception to be thrown from another method. I believe the problem lies only in the FacebookUser.java class (since getRecommendations is recursive method) but I thought it'd be best to also show the UserAccount.java class since the former extends the latter. Any help will be appreciated. Thank you.
Execution:
Exception in thread "main" java.io.InvalidClassException: FacebookUser; local class incompatible: stream classdesc serialVersionUID = 4110981517967863740, local class serialVersionUID = 5032562666539812166
at java.base/java.io.ObjectStreamClass.initNonProxy(Unknown Source)
at java.base/java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
at java.base/java.io.ObjectInputStream.readClassDesc(Unknown Source)
at java.base/java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.base/java.io.ObjectInputStream.readObject0(Unknown Source)
at java.base/java.io.ObjectInputStream.readObject(Unknown Source)
at FacebookUser.readFile(FacebookUser.java:157)
at DriverClass.main(DriverClass.java:12)
FacebookUser.Java
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
public class FacebookUser extends UserAccount implements Serializable{
private String passwordHint;
private ArrayList<FacebookUser> friends;
public FacebookUser(String username, String password) {
super(username, password);
friends = new ArrayList<FacebookUser>();
}
#Override
public void getPasswordHelp() {
System.out.println("Password Hint: " + passwordHint);
}
public void getPasswordHelp(String username) {
if (friends.size() == 0) {
System.out.println("There is no user with that username.");
} else {
for (int i = 0; i < friends.size(); i++) {
if (friends.get(i).toString().equals(username)) {
friends.get(i).getPasswordHelp();
break;
}
if (i == friends.size() - 1) {
System.out.println("There is no user with that username.");
break;
}
}
}
}
void setPasswordHint(String hint) {
passwordHint = hint;
}
void friend(FacebookUser newFriend) {
if (friends.contains(newFriend)) {
System.out.println("That person is already your friend.");
} else {
friends.add(newFriend);
}
}
void friend(String username) {
Scanner s = new Scanner(System.in);
if (friends.size() == 0) {
System.out.println("Please create a password: ");
String password = s.nextLine();
System.out.println("Please create a password hint: ");
String passHint = s.nextLine();
FacebookUser fbu = new FacebookUser(username, password);
fbu.setPasswordHint(passHint);
friends.add(fbu);
} else {
for (int i = 0; i < friends.size(); i++) {
if (friends.get(i).toString().equals(username)) {
System.out.println("That person is already your friend.");
break;
}
if (i == friends.size() - 1) {
System.out.println("Please create a password: ");
String password = s.nextLine();
System.out.println("Please create a password hint: ");
String passHint = s.nextLine();
FacebookUser fbu = new FacebookUser(username, password);
fbu.setPasswordHint(passHint);
friends.add(fbu);
break;
}
}
}
}
void defriend(FacebookUser formerFriend) {
if (friends.contains(formerFriend)) {
friends.remove(formerFriend);
} else {
System.out.println("That person is not your friend.");
}
}
void defriend(String username) {
Scanner s = new Scanner(System.in);
if (friends.size() == 0) {
System.out.println("That person is not your friend.");
} else {
for (int i = 0; i < friends.size(); i++) {
if (friends.get(i).toString().equals(username)) {
System.out.println("Password for " + username + ": ");
String passw = s.nextLine();
if (friends.get(i).getPassword().equals(passw)) {
friends.remove(i);
break;
} else {
System.out.println("Incorrect Password");
break;
}
}
if (i == friends.size() - 1) {
System.out.println("That person is not your friend.");
break;
}
}
}
}
ArrayList<FacebookUser> getRecommendations(FacebookUser friend) {
ArrayList<FacebookUser> recFriends = new ArrayList<FacebookUser>();
for (int i = 0; i < friend.getFriends().size(); i++) {
for (int j = 0; j < recFriends.size(); j++) {
for (int k = 0; k < recFriends.size(); k++) {
if (recFriends.get(j).equals(recFriends.get(k))) {
recFriends.remove(j); // This removes any duplicate friends so there won't be an infinite loop.
break;
}
}
}
recFriends.addAll(friend.getFriends().get(i).getRecommendations(friend)); // This adds the friends' friends' friends and so on into the ArrayList.
}
return recFriends;
}
ArrayList<FacebookUser> getFriends() {
ArrayList<FacebookUser> friendsCopy = new ArrayList<FacebookUser>();
for (int i = 0; i < friends.size(); i++) {
friendsCopy.add(friends.get(i));
}
Collections.sort(friendsCopy, new Comparator<FacebookUser>() {
#Override
public int compare(FacebookUser fb1, FacebookUser fb2) {
return fb1.toString().compareToIgnoreCase(fb2.toString());
}
});
return friendsCopy;
}
public static void writeToFile(FacebookUser facebookUser) throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("FacebookUser.bin"));
oos.writeObject(facebookUser); // This saves the data.
}
public static FacebookUser readFile() throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("FacebookUser.bin"));
FacebookUser facebookUser = (FacebookUser) ois.readObject(); // This reads in the data which is called in the DriverClass class line 12.
return facebookUser;
}
}
UserAccount.java
import java.io.Serializable;
public abstract class UserAccount implements Serializable{
private String username;
private String password;
private boolean active;
public UserAccount(String username, String password) {
this.username = username;
this.password = password;
active = true;
}
public boolean checkPassword(String password) {
if (password.equals(this.password)) {
return true;
} else {
return false;
}
}
public void deactivateAccount() {
active = false;
}
public String getPassword() {
return password;
}
public String toString() {
return username;
}
public boolean checkActive() {
if (active == true) {
return true;
} else {
return false;
}
}
public abstract void getPasswordHelp();
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((username == null) ? 0 : username.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
UserAccount other = (UserAccount) obj;
if (username == null) {
if (other.username != null)
return false;
} else if (!username.equals(other.username))
return false;
return true;
}
}
DriverClass.java
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class DriverClass {
public static void main(String[] args) throws IOException, ClassNotFoundException {
int choice = 0;
String username;
FacebookUser fu0;
try {
fu0 = FacebookUser.readFile();
} catch (FileNotFoundException e) {
fu0 = new FacebookUser("Robert", "password1");
}
while (choice != 5) {
System.out.println(
"1. List Users \n2. Add a User \n3. Delete a User \n4. Get Password Hint \n5. Get Recommendations \n6. Quit");
Scanner s = new Scanner(System.in);
choice = s.nextInt();
switch (choice) {
case 1:
System.out.println(fu0.getFriends());
break;
case 2:
System.out.println("Username: ");
s.nextLine();
username = s.nextLine();
fu0.friend(username);
break;
case 3:
System.out.println("Username: ");
s.nextLine();
username = s.nextLine();
fu0.defriend(username);
break;
case 4:
System.out.println("Username: ");
s.nextLine();
username = s.nextLine();
fu0.getPasswordHelp(username);
break;
case 5:
System.out.println(fu0.getRecommendations(fu0));
break;
case 6:
FacebookUser.writeToFile(fu0);
break;
}
}
}
}
The exception suggests that the SerialVersionUID the JVM generated differs for some instances of the FacebookUser object. If you make your class implement Serializable, it is highly recommended that you explicitly declare the SerialVersionUID variable to avoid exceptions like these.
So in the FacebookUser class you should declare a variable like this:
private static final long serialVersionUID = 42L;
See this answer for more details.
My program has 6 classes so I'm going to try and only post the methods involved with the issue I'm having. I'm trying to add donation objects that get their attributes from reading information from a file. My program wasn't printing out any of the donationList related information so I did a System.out.println(donationList.size()); and it's telling me that there are 0 objects in the list. I've been looking at this for a while and can't figure out where in the process the donation object is failing to be created correctly or added to the arraylist correctly.
This is where I call the method that starts the process.
public static void main(String[] args) {
readAndProcess();
This is the method that starts the process.
public static void readAndProcess() {
final String INPUT_FILENAME = "input/assn2input.txt";
File dataFile = new File(INPUT_FILENAME);
Scanner fileScanner = null;
try {
fileScanner = new Scanner(dataFile);
}catch (FileNotFoundException e) {
System.out.println("File not found exception for file " + e);
System.exit(0);
}
String oneLine;
String [] lineValues;
while(fileScanner.hasNextLine()) {
oneLine = fileScanner.nextLine();
lineValues = oneLine.split(",");
if(lineValues[0].equals("DONOR")) {
if (lineValues[1].equals("ADD") ) {
addDonor(lineValues);
}
else if (lineValues[1].equals("DEL")) {
// call method to delete
}
}
else if ( lineValues[0].equals("Donation")) {
if (lineValues[1].equals("ADD")) {
addDonation(lineValues);
}
else if (lineValues[1].equals("DEL")) {
// call method to delete
}
}
}
}
This is the addDonation method which happens after the readAndProcess method.
public static void addDonation(String [] lineValues) {
Donation donation = new Donation();
setDonationAttributes(donation, lineValues);
if (donorImpl.isIDUnique(donation.getDonorID()) == false &&
donationImpl.isIDUnique(donation.getDonationID()) == true) {
donationImpl.add(donation);
}
else {
System.out.println("ERROR: The Donation either had a non-unique"
+ " donation ID or a unique Donor ID. Was not "
+ "added to list." + donation.toString());
}
}
This is the method that sets the donation object's attributes.
public static Donation setDonationAttributes (Donation donation,
String [] lineValues) {
donation.setDonationID(Integer.parseInt(lineValues[2]));
donation.setDonorID(Integer.parseInt(lineValues[3]));
donation.setDonationDescription(lineValues[4]);
if (donation.checkDescriptionLength() == false) {
System.out.println("ERROR: Donation description is longer "
+ "than 25 characters");
}
donation.setDonationAmount(Double.parseDouble(lineValues[5]));
donation.setDonationDate(lineValues[6]);
if (lineValues[7].equalsIgnoreCase("Y") ) {
donation.setTaxDeductible(true);
}
else {
donation.setTaxDeductible(false);
}
donation.setCheckNumber(Integer.parseInt(lineValues[8]));
if (donation.checkNumberCheck()== false) {
System.out.println("ERROR: Invalid check number is not between 100 "
+ "and 5000: " + lineValues[8]);
}
return donation;
}
This is the method that checks for unique ID for donationID.
public boolean isIDUnique(int donationID) {
int index;
for (index = 0; index < donationList.size(); ++index) {
if (donationID == donationList.get(index).getDonationID() ) {
return false;
}
}
return true;
}
This is the method for checking unique donorID.
public boolean isIDUnique(int donorID) {
int index;
for (index = 0; index < donorList.size(); ++index) {
if (donorID == donorList.get(index).getDonorID() ) {
return false;
}
}
return true;
}
This is the method in the DonationImpl class that adds the object to the arraylist. The instructions for this method told me to set it up as a boolean for whatever reason, I'm not exactly sure why.
public boolean add (Donation donation) {
if (donationList.add(donation)) {
return true;
}
return false;
}
The donationImpl class to show what the arrayList creation looks like.
public class DonationImpl {
// Data Field
private ArrayList<Donation> donationList = new ArrayList<Donation>();
//Getter
public ArrayList<Donation> getDonationList() {return donationList;}
The 1 and 3 in the following examples refer to a donorID. My donorID methods and creation are all working correctly.
Example lines of text:
DONATION,ADD,101,1,Payroll deduction,22.22,07/04/1776,Y,1001
DONATION,ADD,303,3,Anniversary contribution,111.00,07/04/1777,N,2244
You have a typo
else if ( lineValues[0].equals("Donation")) {
should be
else if ( lineValues[0].equals("DONATION")) {
I'm trying to make an application in Java to check my password security.
This is what I already did:
import java.util.Arrays;
public class BruteForce {
public static void main(String[] args) {
String password = "123123";
char[] charset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
BruteForce bf = new BruteForce(charset, 1);
String attempt = bf.toString();
while (true) {
if (attempt.equals(password)) {
System.out.println("Password Found: " + attempt);
break;
}
attempt = bf.toString();
System.out.println("" + attempt);
bf.increment();
}
}
private char[] cs; // Character Set
private char[] cg; // Current Guess
public BruteForce(char[] characterSet, int guessLength) {
cs = characterSet;
cg = new char[guessLength];
Arrays.fill(cg, cs[0]);
}
public void increment() {
int index = cg.length - 1;
while(index >= 0) {
if (cg[index] == cs[cs.length-1]) {
if (index == 0) {
cg = new char[cg.length+1];
Arrays.fill(cg, cs[0]);
break;
}
else {
cg[index] = cs[0];
index--;
}
}
else {
cg[index] = cs[Arrays.binarySearch(cs, cg[index]) + 1];
break;
}
}
}
#Override
public String toString() {
return String.valueOf(cg);
}
}
But I take a long time to get the "123123" as password (Maybe I don't even get it, I'm not sure)...
Is there a better method to do this with upper/lower alphabetical letters and numbers? Thank you.
For example, I am getting the error here- this is just a snippet. I got the error 3 times in 3 different operators.
public boolean delete(String name) {
for (int i = 0; i < directory.length; i++) {
if (directory[i].equalsIgnoreCase(name)) {
directory[i] = null;
return true;
}
else
return false;
}
}
I also have the same error here:
public boolean add(String name) {
if (directory.length == 1024)
return false;
for (int i = 0; i < directory.length; i++) {
if (directory[i].equalsIgnoreCase(name))
return false;
else
directory[directorySize++] = name;
return true;
}
}
And then in my second class (the user interface portion), I keep getting this error: Exception in thread "main" java.lang.NoClassDefFoundError: Directory
Here is the entire code for that class:
import java.io.*;
import java.util.*;
public class DirectoryWithObjectDesign {
public static void main(String[] args) throws IOException {
String directoryDataFile = "Directory.txt";
Directory d = new Directory(directoryDataFile);
Scanner stdin = new Scanner(System.in);
System.out.println("Directory Server is Ready!");
System.out.println("Format: command name");
System.out.println("Enter ^Z to end");
while (stdin.hasNext()) {
String command = stdin.next();
String name = stdin.next();
if (command.equalsIgnoreCase("find")) {
if (d.inDirectory(name))
System.out.println(name + " is in the directory");
else
System.out.println(name + " is NOT in the directory");
}
else if (command.equalsIgnoreCase("add")) {
if (d.add(name))
System.out.println(name + " added");
else
System.out.println(name + " cannot add! " + "no more space or already in directory");
}
else if (command.equalsIgnoreCase("delete")) {
if (d.delete(name))
System.out.println(name + " deleted");
else
System.out.println(name + " NOT in directory");
}
else {
System.out.println("bad command, try again");
}
}
}
}
And here is the code for my directory class:
import java.util.*;
import java.io.*;
public class Directory {
//public static void main(String[] args) {
final int maxDirectorySize = 1024;
String directory[] = new String[maxDirectorySize];
int directorySize = 0;
File directoryFile = null;
Scanner directoryDataIn = null;
public Directory(String directoryFileName) {
directoryFile = new File(directoryFileName);
try {
directoryDataIn = new Scanner(directoryFile);
}
catch (FileNotFoundException e) {
System.out.println("File is not found, exiting!" + directoryFileName);
System.exit(0);
}
while (directoryDataIn.hasNext()) {
directory[directorySize++] = directoryDataIn.nextLine();
}
}
public boolean inDirectory(String name) {
for (int i = 0; i < directory.length; i++) {
if (directory[i].equalsIgnoreCase(name))
return true;
else
return false;
}
}
public boolean add(String name) {
if (directory.length == 1024)
return false;
for (int i = 0; i < directory.length; i++) {
if (directory[i].equalsIgnoreCase(name))
return false;
else
directory[directorySize++] = name;
return true;
}
}
public boolean delete(String name) {
for (int i = 0; i < directory.length; i++) {
if (directory[i].equalsIgnoreCase(name)) {
directory[i] = null;
return true;
}
else
return false;
}
}
public void closeDirectory() {
directoryDataIn.close();
PrintStream directoryDataOut = null;
try {
directoryDataOut = new PrintStream(directoryFile);
}
catch (FileNotFoundException e) {
System.out.printf("File %s not found, exiting!", directoryFile);
System.exit(0);
}
String originalDirectory[] = {"Mike","Jim","Barry","Cristian","Vincent","Chengjun","susan","ng","serena"};
if (originalDirectory == directory)
System.exit(0);
else
for (int i = 0; i < directorySize; i++)
directoryDataOut.println(directory[i]);
directoryDataOut.close();
}
}
The point is that the compiler can't know if your for loop will be entered at all. Therefore you need a final return after the end of the for loop, too. In other words: any path that can possibly be taken within your method needs a final return statement. One easy way to achieve this ... is to have only one return statement; and put that on the last line of the method. This could look like:
Object getSomething() {
Object rv = null; // rv short for "returnValue"
for (int i=0; i < myArray.length; i++) {
if (whatever) {
rv = godKnowsWhat;
} else {
rv = IdontCare;
}
}
return rv;
}
In your second example, the indenting seems to indicate that you have a return in the else statement
directory[directorySize++] = name;
return true;
But when you look closer, you will realize that there are TWO statements after the else
else
directory[directorySize++] = name;
return true;
So this actually reads like
else
directory[directorySize++] = name;
return true;
Meaning: always put {braces} around all your blocks, even for (supposedly) one-liner then/else lines. That helps to avoid such mistakes, when a one-liner turns into a two-liner (or vice versa ;-)
The "NoClassDefFoundException" means: within the classpath that is specified to java ... there is no class Directory.class
To resolve that, you should study what the java classpath is about; and how to set it correctly.
Here is a simple version without any loops. How can I make it loop like "Wrong password. Try again." until user puts the right password instead stopping the program
(or give them 3 chances before it stops)?
import java.util.Scanner;
public class helloworld2
{
public static void main(String[] arg)
{
Scanner q = new Scanner(System.in);
long Pass;
boolean auth = true;
System.out.println("Enter Password :");
Pass = q.nextLong();
if ( Pass != 1234 )
{
System.out.println("Wrong Password!");
auth = false;
}
else
{
System.out.println("Password Confirmed.");
auth = true;
}
if (auth) {
////blablabla
}
else
{
return;
}
}
}
public class helloworld2
{
public static void main(String[] arg)
{
Scanner q = new Scanner(System.in);
long Pass;
boolean auth = true;
boolean rightPassword = false;
while(!rightPassword){//repeat until passwort is correct
System.out.println("Enter Password :");
Pass = q.nextLong();
if ( Pass != 1234 )
{
System.out.println("Wrong Password!");
auth = false;
}
else
{
rightPassword = true;//let the loop finish
System.out.println("Password Confirmed.");
auth = true;
}
}
// Here do what you want to do
//because here the user has entered a right password
}
}