What Exception do I need to add to my try catch block if I want to detect if a user has entered any characters?
This is my code where I want to know if the user hasn't input anything or if the user's input was already saved in an addressbook. I am using an array to store my entries:
public void addEntry() {
entry[counter] = new AddressBookEntry();
entry[counter].setName(JOptionPane.showInputDialog("Enter name: "));
entry[counter].setAdd(JOptionPane.showInputDialog("Enter add: "));
entry[counter].setPhoneNo(JOptionPane.showInputDialog("Enter Phone No.: "));
entry[counter].setEmail(JOptionPane.showInputDialog("Enter E-mail: "));
counter++;
}
Do I need a try-catch or a condition? Here's my complete code:
public class AddressBook {
private AddressBookEntry entry[];
private int counter;
private String SName;
private int notfound = 0;
public static void main(String[] args) {
AddressBook a = new AddressBook();
a.entry = new AddressBookEntry[100];
int option = 0;
try {
while (option != 5) {
String content = "Choose an Option\n\n"
+ "[1] Add an Entry\n"
+ "[2] Delete an Entry\n"
+ "[3] Update an Entry\n"
+ "[4] View all Entries\n"
+ "[5] View Specific Entry\n"
+ "[6] Exit";
option = Integer.parseInt(JOptionPane.showInputDialog(content));
switch (option) {
case 1:
a.addEntry();
break;
case 2:
a.deleteEntry();
break;
case 3:
a.editEntry();
break;
case 4:
a.viewAll();
break;
case 5:
a.searchEntry();
break;
case 6:
System.exit(1);
break;
default:
JOptionPane.showMessageDialog(null, "Invalid Choice!");
}
}
}catch(NumberFormatException e){
JOptionPane.showMessageDialog(null, "Please Choose a Number in the displayed Menu");
}
}
public void addEntry() {
entry[counter] = new AddressBookEntry();
entry[counter].setName(JOptionPane.showInputDialog("Enter name: "));
entry[counter].setAdd(JOptionPane.showInputDialog("Enter add: "));
entry[counter].setPhoneNo(JOptionPane.showInputDialog("Enter Phone No.: "));
entry[counter].setEmail(JOptionPane.showInputDialog("Enter E-mail: "));
counter++;
}
public void viewAll() {
String addText = " NAME\tADDRESS\tPHONE NO.\tE-MAIL ADD\n\n";
int nonNull = 0;
for (int i = 0; i < entry.length; i++) {
if (entry[i] != null) {
addText = addText + entry[i].getInfo() + "\n";
nonNull++;
}
if (nonNull == counter) {
break;
}
}
JOptionPane.showMessageDialog(null, new JTextArea(addText));
}
public void searchEntry() {
SName = JOptionPane.showInputDialog("Enter Name to find: ");
searchMethod();
}
public void searchMethod() {
for (int i = 0; i < counter; i++) {
if (entry[i].getName().equals(SName)) {
JOptionPane.showMessageDialog(null, entry[i].getInfo2());
notfound = 0;
break;
} else {
notfound++;
}
}
if (notfound != 0) {
JOptionPane.showMessageDialog(null, "Name Not Found!");
}
}
public void editEntry() {
SName = JOptionPane.showInputDialog("Enter Name to edit: ");
for (int i = 0; i < counter; i++) {
if (entry[i].getName().equals(SName)) {
entry[i] = new AddressBookEntry();
entry[i].setName(JOptionPane.showInputDialog("Enter new name: "));
entry[i].setAdd(JOptionPane.showInputDialog("Enter new add: "));
entry[i].setPhoneNo(JOptionPane.showInputDialog("Enter new Phone No.: "));
entry[i].setEmail(JOptionPane.showInputDialog("Enter new E-mail: "));
notfound = 0;
break;
} else {
notfound++;
}
}
if (notfound != 0) {
JOptionPane.showMessageDialog(null, "Name Not Found!");
}
}
public void deleteEntry() {
SName = JOptionPane.showInputDialog("Enter Name to delete: ");
for (int i = 0; i < counter; i++) {
if (entry[i].getName().equals(SName)) {
JOptionPane.showMessageDialog(null, "Found!");
entry[i] = null;
break;
}
}
}
}
I am having problem with my addEntry() method, because I want to detect if the user's new added entry was already stored in my addressbook and if the user doesn't typed anything when I ask "Enter Name:" in JOptionPane and still press OK.
Although not much clear about your question, I will try to answer it.
In this case, you can manually create your own exception here like,
throw new MyException();
Since your condition "The user didn't enter any character" is itself not clearer, I would suggest that you can try throwing exception by checking the no of arguments passed on the command-line.
If it's 0 i.e no arguments are passed, you can throw your own exception.
But by itself, no exception will be thrown.
I don't know of any exception, but you can use the length method.
Example:
input=(JOptionPane.showInputDialog(frame1, "what do you want?"));
if(input.length() > 0) {
l1.setText("a " + input + " on the way!");
}
else{
l1.setText("would you please choose something");
}
if length is greater then zero
From your updated question, it appears as if you are talking about user input from dialog boxes. The javadoc says that the showInputDialog methods return either the user's String (which could be empty) or null if the user canceled the dialog.
No exception is thrown. The user canceling the dialog is not "exceptional".
In general, when some method throws an exception and you don't catch it, either the compiler alerts you about this (for checked exceptions) or when the exceptions is thrown on runtime, you see a nice stack trace on the console (standard error). If you don't see this, then either you have caught (and thrown away) this exception, or there is no exception.
The user didn't enter any character by itself is not a condition which causes anyone to throw an exception, we would need more context.
Related
Can anyone help?
Choice 2 isn't working. It is suppose to display the employee ID when the user inputs the employee Name, but when the user enters the name nothing prints. The code has no errors.
public static void main(String[] args) {
int[] emplID={ 42577, 38611, 32051, 28627, 42061, 79451 };//employee ID
int ID = employeeID(emplID);
String[] emplNames= { "Bruce Wayne", "Barry Allen", "Hal Jordan", "Dinah Lance", "Oliver Queen", "Tineil Charles" };// Employee Names
search(emplNames, emplID);
//methods called from main
}
public static int employeeID(int [] emplID) {
//check ID length
for(int i=0; i< emplID.length; i++) {
if((emplID[i] > 10000)&&(emplID[i] < 99999)) {
System.out.print(emplID[i] + " - Valid ID length\n");
}
else {
System.out.println(emplID[i] + " - Invalid ID! ID must be Five digits!\n");
}//end of check length
//check if ID is prime
boolean isPrime = true;
for (int j = 2; j < emplID[i]; j++) {
if (emplID[i] % j == 0) {
System.out.println(emplID[i] + " - not prime");
isPrime = false;
break;
}
}
if(isPrime) System.out.println(emplID[i] + " - valid prime");//end of check prime
}//end of employeeID method
return 0;
}// end of ID checker
// search employee data
public static void search(String[] emplNames, int[]emplID) {
Scanner scan= new Scanner(System.in);
//Menu Choice
System.out.println("Please choose 1 to enter Employee ID or 2 to enter Employee Name:" );
int num = scan.nextInt();//input choice
// Choice 1 to enter ID to display name
if (num == 1) {
System.out.println("Please enter Employee ID:");
int searchID= scan.nextInt();
for(int ID = 0; ID < emplID.length; ID++) {
if (searchID == (emplID[ID])){
System.out.println("Name: "+ emplNames[ID]);
}
}
}
// Choice 2 to enter name to display ID
else if(num == 2) {
System.out.println("Please enter Employee Name");
String searchName= scan.next();
for(int ID = 0; ID< emplID.length; ID++){
if ((searchName.equals(emplNames[ID]))){
System.out.println("ID: " + emplID[ID]);
}
}
}
else
System.out.println("Employee Not Found");
}
}
I copied and pasted your code and ran it on my machine. Yes, choice 2 was not working for me either.
Before reading your code completely my gut feeling was that the cause of failure was in using the Scanner class to get the name of the employee. I have had similar issues in the past and the best move is to learn to use the InputStreamReader and BufferedStreamReader objects.
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
1: I didn't do anything to your main()
public static void main(String[] args) {
int[] emplID={ 42577, 38611, 32051, 28627, 42061, 79451 };//employee ID
int ID = employeeID(emplID);
String[] emplNames= { "Bruce Wayne", "Barry Allen", "Hal Jordan", "Dinah Lance", "Oliver Queen", "Tineil Charles" };// Employee Names
search(emplNames, emplID);
}
2: I didn't do anything to your employeeID() function
public static int employeeID(int [] emplID) {
//check ID length
for(int i=0; i< emplID.length; i++) {
if((emplID[i] > 10000)&&(emplID[i] < 99999)) {
System.out.print(emplID[i] + " - Valid ID length\n");
}
else {
System.out.println(emplID[i] + " - Invalid ID! ID must be Five digits!\n");
}//end of check length
//check if ID is prime
boolean isPrime = true;
for (int j = 2; j < emplID[i]; j++) {
if (emplID[i] % j == 0) {
System.out.println(emplID[i] + " - not prime");
isPrime = false;
break;
}
}
if(isPrime) System.out.println(emplID[i] + " - valid prime");//end of check prime
}//end of employeeID method
return 0;
}// end of ID checker
3: It's in your search() method where I first created the InputStreamReader and the BufferedReader:
public static void search(String[] emplNames, int[]emplID) {
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader buff = new BufferedReader(in);
//Menu Choice
System.out.println("Please choose 1 to enter Employee ID or 2 to enter Employee Name:" );
int num = 0;
try {
num = Integer.parseInt(buff.readLine());
} catch (Exception e) {
e.printStackTrace();
}
4: Since choice 1 works fine, all I did was change your for loop to a for-each loop to make it easier to read.
// Choice 1 to enter ID to display name
if (num == 1) {
System.out.println("Please enter Employee ID:");
int searchID = 0;
try {
searchID = buff.read();
} catch (Exception e) {
e.printStackTrace();
}
for (int i : emplID) {
if (searchID == i) {
System.out.println("Name: " + emplNames[i]);
}
}
5: Here is what I did to make your 2nd Option work. Again, get the String from user via BufferedReader object's readLine() method. Then, it was just letting your for-loop searching for a match. That's it. Afterward, I ran the program and tested it for all the names you had above, works fine.
} else if (num == 2) {
System.out.println("Please enter Employee Name");
String searchName = "";
try {
searchName = buff.readLine();
} catch(Exception e) {
e.printStackTrace();
}
for(int ID = 0; ID< emplID.length; ID++){
if ((searchName.equals(emplNames[ID]))){
System.out.println("ID: " + emplID[ID]);
}
}
} else {
System.out.println("Employee Not Found");
}
}
}
6: Yeah, Scanner has an issue where it either doesn't read the entire line or you need to flush the stream before getting the input. It caused a lot of problems for me in a bunch of easy programs. Then I switched to using the InputStreamReader and BufferedStreamReader combo. Just wrap them in try-catch blocks, and you're fine. Look into it, it will the behavior of your code and your life a lot easier.
7: I hope this was helpful.
I have encountered a problem: I need to be able to filewrite after I have added to the array (dock) and removed from the array (undock) on the fly. But I do not know where to put the flush() and close(). I get errors when I but it after the write function wherever I put them because they have already closed the filewriter. Can you help?
try {
portLog.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
portLog.close();
} catch (IOException e) {
e.printStackTrace();
}
Here is my code:
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
public class Main {
static Scanner scan = new Scanner(System.in);
private static Ship[] dock1 = new Ship[10];
private static Ship[] waitingList = new Ship[10];
static FileWriter portLog;
static DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
//get current date time with Date()
static Date date = new Date();
static {
try {
portLog = new FileWriter("\\Users\\Smith\\Desktop\\PortLog.txt", true);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
menu();
}
public static void menu() {
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("Choose an option: 1-3");
System.out.println("1. Dock");
System.out.println("2. Undock");
System.out.println("3. Status");
int menu = scan.nextInt();
switch (menu) {
case 1:
System.out.println("1. Dock");
dock();
break;
case 2:
System.out.println("2. Undock");
undock();
break;
case 3:
System.out.println("3. Status");
printDock();
printWaitingList();
break;
case 4:
System.out.println("4. Exit");
System.exit(0);
default:
System.out.println("No such option");
break;
}
}
}
public static void dock() {
System.out.println("Enter ship's name: ");
String name = scan.nextLine();
System.out.println("Enter ship's size: ");
String size = scan.nextLine();
System.out.println("Enter the ships dock:");
//Check if the dock number is valid
int i = Integer.valueOf(scan.nextLine());
if (i >= 0 && i < 10 && dock1[i] == null) {
int c = 0;
int co = 0;
int sco = 0;
for (int j = 0; j < dock1.length; j++) {
if (dock1[j] != null && dock1[j].getShipSize().equals("Cargo")) {
c++;
}
if (dock1[j] != null && dock1[j].getShipSize().equals("Container")) {
co++;
}
if (dock1[j] != null && dock1[j].getShipSize().equals("Super-Container")) {
sco++;
}
}
if (c < 10 && co < 5 && sco < 2) {
//Add ship to the dock
dock1[i] = new Ship(name, size);
System.out.println("Enough space you can dock");
System.out.println("Ship has been docked");
try {
portLog.write("\n" + " Docked: " + dock1[i].getShipName() + " Size: " + dock1[i].getShipSize() + " at " + dateFormat.format(date));
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("You cannot dock");
waitingList(name, size);
}
} else {
System.out.println("Couldn't dock");
waitingList(name, size);
}
}
public static void undock() {
System.out.println("Status of ships: ");
printDock();
System.out.println("Enter ship's name to undock: ");
String name = scan.nextLine();
for (int i = 0; i < dock1.length; i++) {
if (dock1[i] != null && dock1[i].getShipName().equals(name)) {
try {
portLog.write("\n" + "Undocked: " + dock1[i].getShipName() + " Size: " + dock1[i].getShipSize() + " at " + dateFormat.format(date));
} catch (IOException e) {
e.printStackTrace();
}
dock1[i] = null;
System.out.println("Ship removed");
/// HERE CHECK IF SHIP IN DOCK
for (int j = 0; j < waitingList.length; j++) {
if (dock1[i] == null && waitingList[j] != null) {
// Add ship to the dock
dock1[i] = new Ship(waitingList[j].getShipName(), waitingList[j].getShipSize());
System.out.println("Move ship from waiting list to dock 1");
waitingList[j] = null;
return;
} else {
return;
}
}
} else {
}
}
System.out.println("Ship not found");
}
public static void waitingList(String name, String size) {
System.out.println("Dock 1 is full, ship will try to be added to Waiting List");
for (int i = 0; i < waitingList.length; i++) {
if (waitingList[i] == null) {
//Add ship to the dock
waitingList[i] = new Ship(name, size);
System.out.println("Enough space added to waiting list");
return;
} else {
}
}
System.out.println("No space on waiting list, ship turned away.");
}
public static void printDock() {
System.out.println("Docks:");
for (int i = 0; i < dock1.length; i++) {
if (dock1[i] == null) {
System.out.println("Dock " + i + " is empty");
} else {
System.out.println("Dock " + i + ": " + dock1[i].getShipName() + " " + dock1[i].getShipSize());
}
}
}
private static void printWaitingList() {
System.out.println("Waiting List:");
for (int i = 0; i < waitingList.length; i++) {
if (waitingList[i] == null) {
System.out.println("Dock " + i + " is empty");
} else {
System.out.println("Dock " + i + ": " + waitingList[i].getShipName() + " " + waitingList[i].getShipSize());
}
}
}
}
That is the thing when you are new to Java, and first start using all static variables within a single class. That is good for the first steps, and getting a hello world printed, or some simple calculations.
But then this approach quickly gets into your way. You see, in the "real" world of OOP, such code is much more of an anti-pattern.
Meaning: that is where you should starting thinking of creating classes of your own. A class has a distinct purpose, like modelling a Ship, or maybe a Dock. Then you add think about the properties that belong into such classes (and for sure: these fields are not static) then.
In that sense, the real answer here is that you "fully" step back and start thinking about better ways to organize the functionalities that you intend to create. As said, in your case, that boils down to define proper Ship/Dock classes. That will then allow you to abstract lower level details, such as "some stuff is stored in files". Because then you can have a DockPersistenceService class for example. Which you pass a list of Dock objects, to somehow persist them. Or that reads a list of Dock objects from a file.
As a general principle, it's a good idea for a resource like this to have a well-defined lifetime. That will typically mean that it's not static. #GhostCat is right that you should really consider a more robust approach, but as a starting point, I'd suggest this.
public static void menu() {
Scanner scan = new Scanner(System.in);
boolean keepProcessing = true; // use this to control the loop, don't call System.exit!
// use try-with-resources to control resource lifetime
try (FileWriter portLog = new FileWriter("\\Users\\Smith\\Desktop\\PortLog.txt", true)) {
while (keepProcessing) {
int choice = scan.nextInt();
switch (choice) {
case 1:
System.out.println("1. Dock");
dock(portLog);
break;
// Other cases skipped for brevity
case 4:
keepProcessing = false;
break;
// Other cases skipped for brevity
}
}
}
}
Then, have your other methods accept the portLog as a parameter.
public static void dock(FileWriter portLog) {
// ...
}
With this setup, the menu method will open the portLog file when it starts up, and close it when the method is finished. It also makes it clearer that the dock, undock, etc. methods require the use of the FileWriter object.
I have a variable B that stores how many user objects have been added in the array userarr. I'm using one line of code that adds a note that the user types in to the B element user object in the userarr array. Here it is:
userarr[login].notes[b] = tempnote;
tempnote is a string variable that temporarily holds the note the user types in, and login stores the user number that you are logged in to. So it assigns the string variable tempnote to the login value user object in the user array, and in element b element in the notes array for that user.
But for some reason there is a problem with this line of code.
I know it is that line of code, because it happens right after you confirm you want to add that note, and there is a println right next to it that never appears.
Here is the method for the whole note thing:
public static void loggedin() {
System.out.println("welcome, " + userarr[login].username + "!");
do{
System.out.println("type 'notes' to list current notes, type 'new' to add notes, type 'delete' to delete a note, or type 'exit' to exit the program.");
switch(scan.nextLine()){
case "exit":
System.out.println("exiting");
login = -1;
break;
case "delete":
break;
case "new":
System.out.println("\n\nType the note.");
String tempnote = scan.nextLine();
System.out.println("note is is now " + tempnote + ". is this what you want? type 'yes' to proceed, or 'no' to enter note again.");
String ch5 = scan.nextLine();
if (ch5.equals("no")) {
break;
} else {
userarr[login].notes[b] = tempnote;
System.out.println("note created!");
b += 1;
}
break;
case "notes":
for (int i=0;i<b;i++) {
System.out.println("Note " + i + ":");
System.out.println(userarr[login].notes[i] + "\n");
}
break;
default:
System.out.println("restarting.");
};
}while(login != -1);
}
Here is the user object thing:
static class user extends TextGame {
String username;
int password;
String[] notes;
public user(String username, int password) {
this.username = username;
this.password = password;
}
}
static user[] userarr = new user[10];
static int a = 0;
static int b = 0;
static int login = -1;
There is no error before i run it. when i get to the part that has the problem it says:
Exception in thread "main" java.lang.NullPointerException
at text.game.TextGame.loggedin(TextGame.java:80)
at text.game.TextGame.login(TextGame.java:53)
at text.game.TextGame.main(TextGame.java:135)
anyone know the problem?
EDIT: It seems necessary to show the whole class, because there is apparently a lot more information people need to know. So here is the whole thing for you to have all the information you need:
package text.game;
import java.util.Scanner;
public class TextGame {
static Scanner scan = new Scanner(System.in);
static class user extends TextGame {
String username;
int password;
String[] notes;
public user(String username, int password) {
this.username = username;
this.password = password;
}
}
static user[] userarr = new user[10];
static int a = 0;
static int b = 0;
static int login = -1;
public static void newuser() {
System.out.println("\n\nType the username for this user.");
String usernameA = scan.nextLine();
System.out.println("Username is now " + usernameA + ". is this what you want? type 'yes' to proceed, or 'no' to enter username again.");
if (scan.nextLine().equals("no")) {
newuser();
} else {
System.out.println("\n\n type the password for this user. (numbers only.)");
int passwordA = scan.nextInt();
System.out.println("user is " + usernameA + " and password is " + passwordA + ". creating user.");
userarr[a] = new user(usernameA, passwordA);
System.out.println("user created!");
a += 1;
}
}
public static void login() {
System.out.println("which account do you want to log into? type the name of a user, or type 'list' to view the users signed in.");
String ch2 = scan.nextLine();
if (ch2.equals("list")){
for (int i=0;i<a;i++) {
System.out.println(userarr[i].username);
}
} else {
for (int i=0;i<a;i++) {if ((userarr[i].username).equals(ch2)){
System.out.println("type the password for this account (USE NUMBERS ONLY).");
int ch4 = scan.nextInt();
if (ch4==userarr[i].password) {
System.out.println("logged in!"); login = i; loggedin();
}else{
System.out.print("incorrect password!");
}
}
}
}
}
public static void loggedin() {
System.out.println("welcome, " + userarr[login].username + "!");
do{
System.out.println("type 'notes' to list current notes, type 'new' to add notes, type 'delete' to delete a note, or type 'exit' to exit the program.");
switch(scan.nextLine()){
case "exit":
System.out.println("exiting");
login = -1;
break;
case "delete":
break;
case "new":
System.out.println("\n\nType the note.");
String tempnote = scan.nextLine();
System.out.println("note is is now " + tempnote + ". is this what you want? type 'yes' to proceed, or 'no' to enter note again.");
String ch5 = scan.nextLine();
if (ch5.equals("no")) {
break;
} else {
userarr[login].notes[b] = tempnote;
System.out.println("note created!");
b += 1;
}
break;
case "notes":
for (int i=0;i<b;i++) {
System.out.println("Note " + i + ":");
System.out.println(userarr[login].notes[i] + "\n");
}
break;
default:
System.out.println("restarting.");
};
}while(login != -1);
}
public static void main(String[] args) {
do {
System.out.println("Welcome to LINCOLN COMP console OS. Type 'new' to create a new user, type 'log' to log in to an existing user, or type 'exit' to leave.\nif you are asked a yes or no question, if you type something other than yes or no, it will default to yes.");
String ch1 = scan.nextLine();
switch (ch1) {
case "new":
if (a==2) {
System.out.println("maximum users have been created. type a username to delete that user, type list to list users, or type back to return.");
String ch3 = scan.nextLine();
if (ch3.equals("list")) {
for (int i=0;i<a;i++) {
if (userarr[i].username==null) {
System.out.println("undefined");
}else{
System.out.println("\n" + userarr[i].username);
};
}
} else if (ch3.equals("back")) {
break;
} else {
for (int i=0;i<a;i++) {
if ((userarr[i].username).equals(ch3)){
System.out.println("type the password for this account (USE NUMBERS ONLY).");
int ch4 = scan.nextInt();
if (ch4==userarr[i].password) {
a --;
userarr[i] = null;
System.out.println("user deleted!");
break;
}else{
System.out.println("incorrect password.");
break;
}
}else if (i==a-1) {
System.out.println("user not found.");
break;
}
}
}
}else {
System.out.println("Initializing user creation method:");
newuser();
}
break;
case "log":
login();
break;
case "exit":
System.out.println("Goodbye!");
System.exit(0);
break;
case "debug":
for (int i=0;i<userarr.length;i++) {
System.out.println(userarr[i]);
}
break;
default:
System.out.println("restarting.");
}
} while (true);
}
}//Note from other user - Extra bracket?
Change
String[] notes;
to something like:
String[] notes = new String[10];
I noticed that you don't appear to be checking if there are next lines/ints whenever you use your scanner's next functions.
Take these two lines from your code for example...
String ch2 = scan.nextLine();
int ch4 = scan.nextInt();
You can check if there is indeed a next int, or next line by using the hasNext functions...
String ch2; //Declared outside of the if-statement for scope reasons
if(scan.hasNextLine()){
//the hasNext functions return true if there is a next line (or int for hasNextInt).
ch2 = scan.nextLine();
}else{
//if something needs to be done in the event that there is no nextLine, do it here
}
int ch4;
if(scan.hasNextInt()){
ch4 = scan.hasNextInt();
}else{
//if something needs to be done in the event that there is no nextInt, do it here
}
This might not solve your issue; however, this at least can prevent many potential issues later. You should always be sure there is more content to get before you get it, and using the hasNext functions make it very easy.
See more at https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
I've created two arrays with ArrayList (java), aList1 and aList2. Both will have a mix of doubles and strings. How do I directly compare the individual contents of aList1 to their corresponding individual contents in aList2 For example, if the first value or string in aList1 doesn't match the first value or string in aList2, there should be a message saying that the two don't match. This should go on for every element of each ArrayList.
Thanks!
EDITED:
Here was my initial attempt:
if (!aList1.get(0).equals(aList2.get(0))) {
JOptionPane.showMessageDialog(null, "#1 is incorrect.");
}
if (!aList1.get(1).equals(aList2.get(1))) {
JOptionPane.showMessageDialog(null, "#2 is incorrect.");
}
And so on, by comparing each element from aList1 to aList2, and seeing if they are not equal (whether they be doubles or strings). The corresponding elements and the sizes of the arrays will always be the same. So for example, if aList1 = {0,1,2,3,4,dog}, aList2 could contain {10,2,5,2,cat}.
EDIT: The whole code.
import javax.swing.JOptionPane;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.ArrayList;
public class KevinMath2 {
static File filename = new File("homework.txt");
static ArrayList <Object> aList = new ArrayList <Object> ();
static String homework = " ";
static File filename2 = new File("homework2.txt");
static ArrayList <Object> aList2 = new ArrayList <Object> ();
static String homework2 = " ";
public static void main(String[] args) {
// TODO Auto-generated method stub
String initialInput = JOptionPane.showInputDialog(null, "Would you like to add answers or check answers?");
String again;
char repeat;
do {
switch (initialInput) {
case "Add answers":
char answerfinal1;
String answerPass = JOptionPane.showInputDialog(null, "Please enter the password");
while (!answerPass.equals("Victor")) {
JOptionPane.showMessageDialog(null, "Incorrect Password. Please try again.");
answerPass = JOptionPane.showInputDialog(null, "Please enter the password.");
}
do {
do {
String options = JOptionPane.showInputDialog(null, "Enter the date of the desired" +
" answers to add (M/D/Y)");
switch (options) {
case "05/29/15":
while (!homework.isEmpty()) {
homework = JOptionPane.showInputDialog("Please enter the answers, in order. After "
+ "the last answer, leave the next answer"
+ " blank, and click OK.");
if (!homework.isEmpty()) aList.add(homework);
}
try {
FileWriter fw = new FileWriter (filename);
Writer output = new BufferedWriter (fw);
int sz = aList.size();
for (int i=0; i < sz; i++) {
output.write(aList.get(i).toString() + "\n");
}
output.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Oops! I cannot create that file.");
}
break;
default:
JOptionPane.showMessageDialog(null, "Please enter a valid date.");
break;
}
} while (!homework.isEmpty());
String final1 = JOptionPane.showInputDialog(null, "Is this correct: " + aList.get(0) + " "
+ aList.get(1) + " " + aList.get(2) + " " +
aList.get(3) + " " + aList.get(4) + "? (Yes or No)");
answerfinal1 = final1.charAt(0);
} while (answerfinal1 == 'n' || answerfinal1 == 'N');
break;
//Need to store the array permanently
case "Check answers": //Need to make it so it stores array of Kevin's answers permanently
char answerfinal2;
String checkPass = JOptionPane.showInputDialog(null, "Please enter the password");
while (!checkPass.equals("Kevin")) {
JOptionPane.showMessageDialog(null, "Incorrect Password. Please try again.");
answerPass = JOptionPane.showInputDialog(null, "Please enter the password.");
}
do {
do {
String options2 = JOptionPane.showInputDialog(null, "Enter the date of the desired" +
" answers to check (M/D/Y)");
switch (options2) {
case "05/29/15":
while (!homework2.isEmpty()) {
homework2 = JOptionPane.showInputDialog("Please enter the answers, in order. After "
+ "the last answer, leave the next answer" +
" blank, and click OK.");
if (!homework2.isEmpty()) aList2.add(homework2);
}
try {
FileWriter fw = new FileWriter (filename2);
Writer output = new BufferedWriter (fw);
int sz = aList2.size();
for (int i=0; i < sz; i++) {
output.write(aList2.get(i).toString() + "\n");
}
output.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Oops! I cannot create that file.");
}
break;
default:
JOptionPane.showMessageDialog(null, "Please enter a valid date.");
}
} while (!homework2.isEmpty());
String final2 = JOptionPane.showInputDialog(null, "Is this correct: " + aList2.get(0) + " "
+ aList2.get(1) + " " + aList2.get(2) + " " +
aList2.get(3) + " " + aList2.get(4) + "? (Yes or No)");
answerfinal2 = final2.charAt(0);
} while (answerfinal2 == 'n' || answerfinal2 == 'N');
int i = 0; // counter variable
if (aList.size() == aList2.size()) { // Check if both lists are equal
for (Object obj : aList) { // iterate through any list
if (obj.getClass() == String.class) { // find if it's a string
if (!aList.get(i).equals(aList2.get(i))) {
JOptionPane.showMessageDialog(null, "#" + i + " is wrong.");
}
}
if (obj.getClass() == Double.class) { // or a double
if (!aList.get(i).equals(aList2.get(i))) {
JOptionPane.showMessageDialog(null, "#" + i + " is wrong.");
}
}
i++;
}
}
break;
default:
JOptionPane.showMessageDialog(null, "Please enter a valid option.");
break;
}
again = JOptionPane.showInputDialog(null, "Would you like to check another answer, or "+
"add another answer? (Yes or No)");
repeat = again.charAt(0);
} while (repeat == 'y' || repeat == 'Y');
JOptionPane.showMessageDialog(null, "Thanks for using this program");
}
}
Try using a for loop to iterate through the first ArrayList and use the counter ('i' in the example below) from that for loop to compare each of the indices that you loop through using the get method provided by ArrayList.
for (int i = 0; i < aList1.size(); i++) {
if (!aList1.get(i).equals(aList2.get(i)))
//output whatever you want it to say
}
Edit: changed to .equals instead of == as suggestion. Good catch.
Compare their datatypes of both the elements of your list if they match then try to compare their contents
For comparing the datatype follow the below mentioned code
int a = 10;
Object o = a;
System.out.println(o.getClass().getSimpleName());
If the datatype matches then try to compare their contents
I agree with coal175s answer but since you say you are mixing types in your arrayLists, you should your the .equals() method to compare them.
if !(aList1.get(i).equals(aList2.get(i))) {
Two things to consider:
Do both ArrayList have the same size
When you're checking elements, must they be the same data type, or can we cast everything to a String and then compare. I will assume they must be the same data type.
Having said that:
public static void main(String[] args) throws Exception {
List<Object> list1 = new ArrayList<>(Arrays.asList(1234, 123.45, "999", 444.444, 999.999));
List<Object> list2 = new ArrayList<>(Arrays.asList("1234", 123.45, "9991", 444.444));
for (int i = 0; i < list1.size(); i++) {
// Only check against parallel list if the index is in the bounds
if (i < list2.size()) {
// Check if the data types match
if (!list1.get(i).getClass().getName().equals(list2.get(i).getClass().getName())) {
System.out.println(String.format("%s: %s != %s: %s",
list1.get(i).getClass().getName(), list1.get(i),
list2.get(i).getClass().getName(), list2.get(i)));
}
// Check if the values match if the datatypes match
else if (!list1.get(i).equals(list2.get(i))) {
System.out.println(String.format("%s != %s", list1.get(i), list2.get(i)));
}
}
}
}
Results (999.999 from list1 does not get checked):
java.lang.Integer: 1234 != java.lang.String: 1234
999 != 9991
You should initialise your List object with Object generics i.e. List<Object> list = new ArrayList<>(); so you can add both String and Double in your list.
Here is an ideal solution to compare two arrays.
List<Object> aList1 = new ArrayList<Object>();
List<Object> aList2 = new ArrayList<Object>();
aList1.add("abc");
aList1.add(25);
aList2.add("abc");
aList2.add(25);
int i = 0; // counter variable
if (aList1.size() == aList2.size()) { // Check if both lists are equal
for (Object obj : aList1) { // iterate through any list
if (obj.getClass() == String.class) { // find if it's a string
if (aList1.get(i).equals(aList2.get(i))) {
JOptionPane.showMessageDialog(null, (i+1) + " is correct.");
} else {
JOptionPane.showMessageDialog(null, (i+1) + " is incorrect.");
}
}
if (obj.getClass() == Double.class) { // or a double
if (aList1.get(i).equals(aList2.get(i))) {
JOptionPane.showMessageDialog(null, (i+1) + " is correct.");
} else {
JOptionPane.showMessageDialog(null, (i+1) + " is incorrect.");
}
}
if (obj.getClass() == Integer.class) {
JOptionPane.showMessageDialog(null, "Integer is found");
}
i++;
}
}
Your code is very hard to follow, when you write a program please try to follow Java conventions.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class KevinMath2 {
static File filename = new File("homework.txt");
static ArrayList<Object> aList = new ArrayList<Object>();
static String homework = "";
static File filename2 = new File("homework2.txt");
static ArrayList<Object> aList2 = new ArrayList<Object>();
static String homework2 = "";
static String answerPass = "";
static final int TOTAL_QUESTIONS = 5;
public static void main(String[] args) {
String initialInput = JOptionPane.showInputDialog(null,
"Enter Add answers / Check answers to continue");
switch (initialInput) {
case "Add answers":
answers("Victor", aList, filename);
int choice = JOptionPane.showConfirmDialog(null,
"Would you like to compare your answers?", "Yes/No", JOptionPane.YES_NO_OPTION);
if (choice == JOptionPane.YES_OPTION) {
answers("Kevin", aList2, filename2);
checkAnswers(aList, aList2);
}
break;
// Need to store the array permanently
case "Check answers": // Need to make it so it stores array of
// Kevin's answers permanently
answers("Kevin", aList2, filename2);
if (aList.size() == 0) {
JOptionPane.showMessageDialog(null,
"Please add answers to compare.");
answers("Victor", aList, filename);
}
checkAnswers(aList, aList2);
break;
default:
JOptionPane.showMessageDialog(null, "Please enter a valid option.");
break;
}
// exit the program
JOptionPane.showMessageDialog(null, "Thanks for using this program");
}
public static void answers(String pass, ArrayList<Object> list, File f) {
answerPass = JOptionPane.showInputDialog(null,
"Please enter the password");
// validate user
while (!answerPass.equals(pass)) {
JOptionPane.showMessageDialog(null,
"Incorrect Password. Please try again.");
answerPass = JOptionPane.showInputDialog(null,
"Please enter the password.");
}
// add answers
String final1 = "";
do {
clearFile(f);
list.clear();
// validate the date of the answers
String options = JOptionPane.showInputDialog(null,
"Enter the date of the desired" + " answers (MM/DD/YY)");
// add your answers
enterAnswers(options, list, f);
// verify the answers
final1 = JOptionPane.showInputDialog(null, "Is this correct: "
+ list.get(0) + " " + list.get(1) + " " + list.get(2) + " "
+ list.get(3) + " " + list.get(4) + "? (Y/N)");
} while (final1.charAt(0) == 'n' || final1.charAt(0) == 'N');
}
public static void enterAnswers(String options, ArrayList<Object> list,
File f) {
switch (options) {
case "05/29/15":
boolean valid = false;
for (int i = 0; i < 5; i++) {
while (!valid) {
homework = JOptionPane
.showInputDialog("Please enter your answer for question "
+ (i + 1));
if (!homework.isEmpty())
valid = true;
}
list.add(homework);
valid = false;
}
writeFile(f, list); // write the answers to a file
break;
default:
JOptionPane.showMessageDialog(null, "Please enter a valid date.");
}
}
public static void writeFile(File filename, ArrayList<Object> list) {
try {
FileWriter fw = new FileWriter(filename);
Writer output = new BufferedWriter(fw);
for (int j = 0; j < list.size(); j++) {
output.write(list.get(j) + "\n");
}
output.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null,
"Oops! I cannot create that file.");
}
}
public static void clearFile(File filename) {
try {
FileWriter fw = new FileWriter(filename);
Writer output = new BufferedWriter(fw);
output.write("");
output.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null,
"Oops! I cannot create that file.");
}
}
public static void checkAnswers(ArrayList<Object> a, ArrayList<Object> b) {
int i = 0; // counter variable
if (a.size() == b.size()) { // Check if both lists are
// equal
for (Object obj : a) { // iterate through any list
if (obj.getClass() == String.class) { // find if it's a
// string
if (!a.get(i).equals(b.get(i))) {
JOptionPane.showMessageDialog(null, "#" + i
+ " is wrong.");
}
}
if (obj.getClass() == Double.class) { // or a double
if (!a.get(i).equals(b.get(i))) {
JOptionPane.showMessageDialog(null, "#" + i
+ " is wrong.");
}
}
if (obj.getClass() == Integer.class) { // or an integer
if (!a.get(i).equals(b.get(i))) {
JOptionPane.showMessageDialog(null, "#" + i
+ " is wrong.");
}
}
i++;
}
}
}
}
Answer is based on the assumption
Add answers to an ArrayList.
Compare your answers from another ArrayList.
You aren't comparing your answers from the written files.
You are writing your 'Added answers' to a file, but you aren't reading that file back again to compare against your 'Check answers'. To do that, write another method to read in the homework.txt file, store each line to your aList, then compare against aList2.
I have an Address Book Program that [1] adds Entry [2] delete entry [3] update/edit entry [4] view all entry and [5] view specific entry..
Entries were stored in an Array entry[] like:
entry[counter] = new AddressBookEntry();
It all runs properly but the thing is... i want there was a checking if the user's input name was already used or if the user doesn't typed anything when i ask "Enter Name: "
here's my addEntry() method:
public void addEntry() {
entry[counter] = new AddressBookEntry();
entry[counter].setName(JOptionPane.showInputDialog("Enter name: "));
entry[counter].setAdd(JOptionPane.showInputDialog("Enter add: "));
entry[counter].setPhoneNo(JOptionPane.showInputDialog("Enter Phone No.: "));
entry[counter].setEmail(JOptionPane.showInputDialog("Enter E-mail: "));
counter++;
}
It allows user input any Entry he likes... but no checking if the name is already used and if the user leave the "Enter Name: " blank it still allows the user to proceed to the "Enter Add.: "
here's my complete code in my main program:
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
public class AddressBook {
private AddressBookEntry entry[];
private int counter;
private String SName;
private int notfound = 0;
public static void main(String[] args) {
AddressBook a = new AddressBook();
a.entry = new AddressBookEntry[100];
int option = 0;
try {
while (option != 5) {
String content = "Choose an Option\n\n"
+ "[1] Add an Entry\n"
+ "[2] Delete an Entry\n"
+ "[3] Update an Entry\n"
+ "[4] View all Entries\n"
+ "[5] View Specific Entry\n"
+ "[6] Exit";
option = Integer.parseInt(JOptionPane.showInputDialog(content));
switch (option) {
case 1:
a.addEntry();
break;
case 2:
a.deleteEntry();
break;
case 3:
a.editEntry();
break;
case 4:
a.viewAll();
break;
case 5:
a.searchEntry();
break;
case 6:
System.exit(1);
break;
default:
JOptionPane.showMessageDialog(null, "Invalid Choice!");
}
}
}catch(NumberFormatException e){
JOptionPane.showMessageDialog(null, "Please Choose a Number in the displayed Menu");
}
}
public void addEntry() {
entry[counter] = new AddressBookEntry();
entry[counter].setName(JOptionPane.showInputDialog("Enter name: "));
entry[counter].setAdd(JOptionPane.showInputDialog("Enter add: "));
entry[counter].setPhoneNo(JOptionPane.showInputDialog("Enter Phone No.: "));
entry[counter].setEmail(JOptionPane.showInputDialog("Enter E-mail: "));
counter++;
}
public void viewAll() {
String addText = " NAME\tADDRESS\tPHONE NO.\tE-MAIL ADD\n\n";
int nonNull = 0;
for (int i = 0; i < entry.length; i++) {
if (entry[i] != null) {
addText = addText + entry[i].getInfo() + "\n";
nonNull++;
}
if (nonNull == counter) {
break;
}
}
JOptionPane.showMessageDialog(null, new JTextArea(addText));
}
public void searchEntry() {
SName = JOptionPane.showInputDialog("Enter Name to find: ");
searchMethod();
}
public void searchMethod() {
for (int i = 0; i < counter; i++) {
if (entry[i].getName().equals(SName)) {
JOptionPane.showMessageDialog(null, entry[i].getInfo2());
notfound = 0;
break;
} else {
notfound++;
}
}
if (notfound != 0) {
JOptionPane.showMessageDialog(null, "Name Not Found!");
}
}
public void editEntry() {
SName = JOptionPane.showInputDialog("Enter Name to edit: ");
for (int i = 0; i < counter; i++) {
if (entry[i].getName().equals(SName)) {
entry[i] = new AddressBookEntry();
entry[i].setName(JOptionPane.showInputDialog("Enter new name: "));
entry[i].setAdd(JOptionPane.showInputDialog("Enter new add: "));
entry[i].setPhoneNo(JOptionPane.showInputDialog("Enter new Phone No.: "));
entry[i].setEmail(JOptionPane.showInputDialog("Enter new E-mail: "));
notfound = 0;
break;
} else {
notfound++;
}
}
if (notfound != 0) {
JOptionPane.showMessageDialog(null, "Name Not Found!");
}
}
public void deleteEntry() {
SName = JOptionPane.showInputDialog("Enter Name to delete: ");
for (int i = 0; i < counter; i++) {
if (entry[i].getName().equals(SName)) {
JOptionPane.showMessageDialog(null, "Found!");
entry[i] = null;
break;
}
}
}
}
Hope you can can help me I am new in Java and I really don't what to add in my code for checking.
* What should I add in my addEntry() method to check if the name was already used or no name entered?
* Do I need a condition like in my searchMethod()?
An address book tends to be a thing where given a name, you look up an address, and other information.
so this falls under a general pattern where you have a Key (the name) and a value (the other information)
When ever you see this, you want to think of using a Map
So, i'd recommend instead of putting your AddressBookEntry's in an array, use a map like this
Map<String, AddressBookEntry> addressBook = new HashMap<String, AddressBookEntry>();
then when you want to add a new entry do
addressBook.put("John", new AddressBookEntry());
the nice thing about a map is that you can only have one entry for the same person.
So you don't have to worry about what happens if you put John in the book twice. It will only allow one in there.