I have a "bank" program, with the following chunk of code:
private void doPayment(JTextField accountNumField, JTextField paymentField)
{
int accountNum = Integer.parseInt(accountNumField.getText());
double paymentAmt = Double.parseDouble(paymentField.getText());
String paymentProcessed = "-RECEIPT OF PAYMENT-" + "\n\n" + "Account Number:" + " " + accountObject.getAccountNum() + "Beginning Balance:" + " " + accountObject.getBegBalance()
+ "Payment Amount:" + " " + accountObject.getPaymentAmount() + "Ending Balance:" + " " + accountObject.getEndBalance();
String errorMsg = "ERROR: ACCOUNT NUMBER" + " " + "[" + accountObject.getAccountNum() + "]" + " " + "NOT FOUND. PLEASE VERIFY THAT THE ACCOUNT INFORMATION IS VALID AND CORRECT.";
if (accountsArrayList.contains(accountNum))
{
accountObject.transactionTwo(paymentAmt);
JOptionPane.showMessageDialog(null, paymentProcessed, "PAYMENT PROCESSED SUCCESSFULLY", JOptionPane.PLAIN_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(null, errorMsg, "INVALID ACCOUNT ERROR", JOptionPane.PLAIN_MESSAGE);
}
}
In theory, after the user creates the account for the client, he/she navigates to a "Process Payment" window and enters two things: accountNum and paymentAmt then hits submit, at which point the doPayment method is called.
This method is supposed to work such that the program iterates through the accountsArrayList which contains THREE items: lastName, firstName, and accountNum. If it finds that the accountNum provided matches a prexisting accountNum in the arrayList, then the transaction is processed accordingly. If no matching accountNum can be found then it returns an error message.
At present, it just returns the error message in the else part of the if-else. I thought that the contains(item) method automatically iterates through the Arraylist. If that isn't the case, do I need an enhanced FOR-loop?
if (accountsArrayList.contains(accountNum))
accountsArrayList is a ArrayList which contains Objects of type Account.
contains returns true only if accountsArrayList contains an Object type Account given as argument. In your code, accountNum is a int
so the compiler reads it like if(Account == INTEGER)
You have to go throw each Account in your ArrayList and get it's accountNum and than compare the values.
for(int i = 0; i < accountsArrayList.size; i++){
if(accountsArrayList.get(i).accountNum == accountNum){
//success
}
else {
//error
}
}
Related
Sorry for my English, but how am I suppose to run the ERROR MESSAGE without repeating 3 times?
This is the original one, if I run the ERROR JOptionPane it will repeat 3 times
String name = JOptionPane.showInputDialog(null, "Enter the Student name to search:", "Input", JOptionPane.QUESTION_MESSAGE);
String data = ("Cannot find the student \"" + name + "\"!!");
for (int i = 0; i < student.length; i++){
if(name.equals(student[i].getName())){
data = ("\n Course \t Admin# \t Name \n" + student[i].getName() + student[i].getAdminNum() + student[i].getCourse() + student[i].getGpa() + student[i].getNewModule() + "\n");
JOptionPane.showMessageDialog(null, data, "Message", JOptionPane.INFORMATION_MESSAGE);
}
Else{
JOptionPane.showMessageDialog(null, data, "Message", JOptionPane.ERROR_MESSAGE);
}
And this is the current one, which the if else statement is wrong as I couldn't read the original data
String name = JOptionPane.showInputDialog(null, "Enter the Student name to search:", "Input", JOptionPane.QUESTION_MESSAGE);
String data = ("Cannot find the student \"" + name + "\"!!");
for (int i = 0; i < student.length; i++){
if(name.equals(student[i].getName())){
data = ("\n Course \t Admin# \t Name \n" + student[i].getName() + student[i].getAdminNum() + student[i].getCourse() + student[i].getGpa() + student[i].getNewModule() + "\n");
}
}
if(data != data){
JOptionPane.showMessageDialog(null, data, "Message", JOptionPane.INFORMATION_MESSAGE);
}
else {
JOptionPane.showMessageDialog(null, data, "Message", JOptionPane.ERROR_MESSAGE);
}
I'm so sorry if there is any misconception thinking passes to you all due to my broken English.
If i undertand your answer, you are finding the "continue" function.
This one breaks de for loop.
https://www.w3schools.com/java/java_break.asp
Create a local variable of name say not_found (int) and increment this found variable in else part instead of showing Dialog everytime.
After end of for loop, check for found variable and display dialog box according to your requirements.
int not_found=0;
String name = JOptionPane.showInputDialog(null, "Enter the Student name to
search:", "Input", JOptionPane.QUESTION_MESSAGE);
String data = ("Cannot find the student \"" + name + "\"!!");
for (int i = 0; i < student.length; i++){
if(name.equals(student[i].getName())){
data = ("\n Course \t Admin# \t Name \n" + student[i].getName()
+ student[i].getAdminNum() + student[i].getCourse() + student[i].getGpa() +
student[i].getNewModule() + "\n");
JOptionPane.showMessageDialog(null, data, "Message",
JOptionPane.INFORMATION_MESSAGE);
}
else{
not_found++:
}
if(not_found!=0){
JOptionPane.showMessageDialog(null, data,
"Message",OptionPane.ERROR_MESSAGE);
}
I'm currently trying to create a lexical analyzer in Java, and I'm having some difficulties getting the analyzer to analyze each character entered. I currently have it analyzing the code with spaces being put in between each character, but the requirements are that the analyzer should be able to detect "(sum" as "(" and "sum", so analyzing using spaces to separate them doesn't work.
My code isn't very efficient, but it currently works to analyze the entered text by using spaces in between the two. Is there a way to analyze each character entered, rather than using " " to separate them?
Here is my code:
String input = JOptionPane.showInputDialog("Enter the Math Problem:");
//input is "(sum + 47) / total"
StringTokenizer st = new StringTokenizer(input, " ");
JOptionPane.showMessageDialog(this,st.countTokens());
//Displays the header to the information table
jTextArea1.append("John D. Student, CSCI4200-DA, Fall 2018, Lexical Analyzer \n" +
"******************************************************************************** \n \n");
//Displays the input value
jTextArea1.append("Input: " + input + "\n");
while(st.hasMoreTokens()) {
//Begin displaying the next token
jTextArea1.append("Next token is: ");
String nextItem = st.nextToken();
if("(".equals(nextItem)) {
jTextArea1.append("LEFT_PAREN" + " " + "Next lexeme is " + nextItem + "\n");
}
else if("sum".equals(nextItem)) {
jTextArea1.append("IDENT" + " " + "Next Lexeme is " + "sum" + "\n");
}
else if("+".equals(nextItem)) {
jTextArea1.append("ADD_OP" + " " + "Next lexeme is " + nextItem + "\n");
}
else if("47".equals(nextItem)) {
jTextArea1.append("INT_LIT" + " " + "Next lexeme is " + "47" + "\n");
}
else if(")".equals(nextItem)) {
jTextArea1.append("RIGHT_PAREN" + " " + "Next Lexeme is " + nextItem + "\n");
}
else if("/".equals(nextItem)) {
jTextArea1.append("DIV_OP" + " " + "Next lexeme is " + nextItem + "\n");
}
else if("total".equals(nextItem)) {
jTextArea1.append("IDENT" + " " + "Next lexeme is " + "total" + "\n");
}
else {
jTextArea1.append("Unknown Character \n");
}
}
//Once the tokens are done, display the finish message
if(!st.hasMoreTokens()) {
jTextArea1.append("******************************************************************************** \n \n");
jTextArea1.append("Next token is: END_OF_FILE" + " " + "Next lexeme is EOF \n");
jTextArea1.append("Lexical analysis of the program is complete!");
}
}
As I commented above need more delimiters for tokenizing.
StringTokenizer st = new StringTokenizer(input, " ()+-");
Is a starting example of what I mean, white space, parentheses, plus and minus. Add more characters to the delimiter string to tokenize by those as well.
You should never see if a string token equals a certain number this will block further progress.
Use something like
int newnum = Integer.ParseInt(nextItem);
after you do an initial check to see if it an integer of course.
I'm completely new to Java and need some help. I'm trying to add results for each attempt in a competition but I got stuck. So far I have the first part that works but without any results added and then I tried to find a way to add results while counting allowed attempts (which are different for each discipline) but without success. What would be the best way both to count attempts and to add results for each attempt?`
private void addResult() {
System.out.print("Enter the number of the participant you would like to add results for: ");
int number = scan.nextInt();
scan.nextLine();
while (number < 0) {
System.out.println("Error: must be greater than or equal to zero!");
number = scan.nextInt();
scan.nextLine();
}
System.out.print("Enter the name of the event you would like to see results for: ");
String event = scan.nextLine();
Participant p = findParticipantByNumber(number);
Event e = findEventByName(event);
if (p == null) {
System.out.println("No participant with number " + number + " found!");
} else if (e == null) {
System.out.println("No event called " + event + " found!");
} else {
System.out.print("Results for " + p.getFirstName() + " " + p.getLastName() +
" from " + p.getTeam() +
" in " + e.getEventName() + ":" + " " + p.getResult() );
scan.nextLine();
Result r = new Result(e, p);
p.addResult(r);
}
}
I would store a HashMap of attempts as an instance variable in the Participant class, where the keys are Strings representing the events and the value corresponding to each key is the number of attempts so far for that event. You could call this map attemptsByEvent and have getter and setter methods for it in Participant. If you need, you can take a look at this page from TutorialsPoint about how to create and populate maps, and what they are.
You should also make a map that is accessible from within addResult() which has Strings representing the events as keys and the maximum allowed attempt for that event as the values. You could call this map attemptMaximums.
Then, you can modify your final block of code to check the number of attempts so far before adding the result. You should also increment the value in the Participant's map if you do add results for an attempt.
else {
System.out.print("Results for " + p.getFirstName() + " " + p.getLastName() +
" from " + p.getTeam() +
" in " + e.getEventName() + ":" + " " + p.getResult() );
scan.nextLine();
Result r = new Result(e, p);
int attempts = p.getAttemptsByEvent().get(e);
if(attempts < attemptMaximums.get(e)){
p.addResult(r);
p.getAttemptsByEvent().put(e, attempts+1);
}
}
This is my first time posting to this site, so if I get any formatting wrong, please be easy on me Lol
I'm writing a Java program that needs to look up a part number from an inventory, and then print the part number along with the data following it. The code is only printing out the information at the top of the file, and then repeating my else statement 5 times.
Here is the code:
package inventory;
import java.util.Scanner;
import java.io.*;
public class inventory
{
public static void main(String[] args) throws IOException
{
Scanner keyboard = new Scanner(System.in);
// File Information
String parts;
File inventoryFile;
FileWriter inventoryFW;
PrintWriter inventoryPW;
Scanner inventorySC;
//User Information
String userChoice;
// Part Information
String partID, partFileID, partFileDesc, partFileLoc, partDesc, partLoc;
double partFilePrice, partPrice;
int partFileQuan, partQuan;
userChoice = ("A");
// Loop
if(userChoice.equalsIgnoreCase("Q"))
System.exit(0);
else
while(!userChoice.equalsIgnoreCase("Q"))
{
// Get Employee Decision
System.out.println("Please choose a letter: \n"
+ "L - Look Up Part \n"
+ "A - Add to Inventory File \n"
+ "E - Erase From Inventory File \n"
+ "G - Generate a Sales Slip \n"
+ "I - Add Quantity to Inventory File \n"
+ "D - Display Inventory \n"
+ "Q - Quit \n"
+ "Selection: ");
userChoice = keyboard.nextLine();
// Process User Choice
if(userChoice.equalsIgnoreCase("L"))
{ // Choice L
// Look Up Part
System.out.println("Enter Part I.D. Number: ");
partID = keyboard.nextLine();
// Do until partID is equal to partFileID
parts = "inventoryFile.txt";
inventoryFile = new File(parts);
inventorySC = new Scanner(inventoryFile);
partFileID = "0";
partFileDesc = "0";
partFilePrice = 0;
partFileLoc = "0";
partFileQuan = 0;
while(inventorySC.hasNextLine())
{
String lineFromFile = inventorySC.nextLine();
if(lineFromFile.contains(partID))
{
partFileDesc = inventorySC.nextLine();
partFilePrice = inventorySC.nextDouble();
inventorySC.nextLine();
partFileLoc = inventorySC.nextLine();
partFileQuan = inventorySC.nextInt();
System.out.println("Part I.D. Number: " + partFileID + "\n");
System.out.println("Part Description: " + partFileDesc + "\n"
+ "Part Price: " + partFilePrice + "\n"
+ "Part Location: " + partFileLoc + "\n"
+ "Part Quantity: " + partFileQuan);
}
else
System.out.println("Sorry, this part cannot be found");
}
}
}
}
}
And here is the datafile I am trying to pull from:
1234567
Clutch
45.68
Warehouse B
8
1234
Brake
66.78
Warehouse A
4
For example, if the user entered part number "1234" the program should search for that part number in the file, and then display:
1234
Brake
66.78
Warehouse A
4
Sorry about any poor code formatting, I have been fighting with this for a while now.
Any help would be greatly appreciated.
There are a few issues.
The contains will have multiple matches.
You will print "not found every line" you don't find.
You are not breaking out of the loop.
boolean found = false;
while(inventorySC.hasNextLine()){
String lineFromFile = inventorySC.nextLine();
if(lineFromFile.equals(partID)) {
partFileDesc = inventorySC.nextLine();
partFilePrice = inventorySC.nextLine();
partFileLoc = inventorySC.nextLine();
partFileQuan = inventorySC.nextLine();
System.out.println("Part I.D. Number: " + partFileID + "\n");
System.out.println("Part Description: " + partFileDesc + "\n"
+ "Part Price: " + partFilePrice + "\n"
+ "Part Location: " + partFileLoc + "\n"
+ "Part Quantity: " + partFileQuan);
found = true;
break;
}
}
if(!found)
System.out.println("Sorry, this part cannot be found");
Your issue is that you are only skipping to the next line if the part list doesn't contain your part value. You actually want to skip down 5 lines if the part is not on the 'next line'.
In your "else" statement, you'll just want to call the inventorySC.nextLine(); 4 more times to get to the next place in the file you actually want to check for a part number.
If you want the 'not found' condition to reflect more effectively that the part number actually wasn't found at all, you'll want to move that message to after it could have scanned the whole file. Set a boolean with a name like 'found' to false before the file scan. If you enter your 'contains' condition because there is a part number in the file that contains your input, set the 'found' equal to true.
At the end if the 'found' is still 'false', you can output the 'not found' message.
As MadProgrammer commented above, you'll need to use 'equals' instead of 'contains'- this is why you match on the first entry. When you find a match and output it, you need to exit the while loop using a 'break' - otherwise you output the else value for each line left over (as is happening to you). But there is one other problem in that you may need to read an entire record - not just the first line of the record - when there is no match so you don't get screwed up when an inventory item has a quantity of 1234 when searching for part number 1234.
I have been creating a program that is to add search delete bookings etc...
After hours I finally thought I was making progress but when I delete a booking my program finds the correct booking returns the correct information for that booking but deletes a different booking.
I have attached the files in a zip as if I displayed them they would take up lots of screen space. The program has been made in BlueJay.
Code for decleration and adding of objects into my array list
public Hostel(String hostelName)
{
this.hostelName = "Newcastle Hostel";
bookings = new ArrayList<Booking>();
}
public String getHostelName()
{
return hostelName;
}
public String addBooking(String roomID, String roomType, String guest)
{
if (roomID.equals(""))
return "Error Please Entre Room ID";
else if (roomType.equals(""))
return "Error Please Entre Room Type";
else if (guest.equals(""))
return "Error Please Entre Guest Name";
bookings.add(new Booking(roomID,roomType,guest));
return "Room " + roomID + " " + roomType + " Has Been Booked For " + guest;
}
This is taken from my hostel class
public String deleteBooking(String roomID)
{
int index = 0;
for ( Booking s : bookings )
{
if ( s.getRoomID().equals(roomID))
{
//return "Room ID: " + roomID + " Room Type: " + s.getRoomType() + " Guest: " + s.getGuest();
String deleteMessage = "Room ID: " + roomID + " Room Type: " + s.getRoomType() + " Guest: " + s.getGuest();
int response = JOptionPane.showConfirmDialog(null, deleteMessage, "Confirm Delete",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (response == JOptionPane.NO_OPTION)
{
} else if (response == JOptionPane.YES_OPTION)
{
bookings.remove(index);
}
index++;
}
}
return " Cannot find room";
}
this is taken from my GUI class
else if (item.equals("Cancel Booking"))
{
newBookingButton.setEnabled(false);
cancelBookingButton.setEnabled(false);
String roomID = JOptionPane.showInputDialog(this, "Enter a room ID", "Delete a Booking", JOptionPane.QUESTION_MESSAGE);
output.setText(hostel.deleteBooking(roomID));
newBookingButton.setEnabled(true);
cancelBookingButton.setEnabled(true);
}
Any additonal code needed either ask or there is a full copy in the link above thanks
Your loop only increments the index if the room ID of the current room is equal to the ID of the room to delete. The line
index++;
should be out of the if block.
EDIT:
The other problem is that you're trying to remove elements a collection while iterating on it. This is only possible if you use an Iterator to iterate over the collection, and use the iterator's remove method to remove the current element. Note that even if it was possible, since you remove the element at the given index, the index should not be incremented since you have just removed the element at this index.
Example of using an iterator:
for (Iterator<Booking> it = bookings.iterator(); it.hasNext(); ) {
Booking b = it.next();
if (...) {
it.remove();
}
}
Basically when s.getRoomID().equals(roomID) is true your if block is executed so no matter what is the response of the user your index is incremented. So, do this:
if ( s.getRoomID().equals(roomID))
{
//your code
}
index++
I just looked into your code, and seems like you are trying to iterate over a collection and also modifying the values at the same time. With enhanced for loop, such things do give errors, so instead of using the enhanced for loop, you must use a normal for loop. So I had modified your deleteBookings Method for the respective change.
public String deleteBooking(String roomID)
{
//for ( Booking s : bookings )
for (int i = 0; i < bookings.size(); i++)
{
Booking s = bookings.get(i);
if ( s.getRoomID().equals(roomID))
{
//return "Room ID: " + roomID + " Room Type: " + s.getRoomType() + " Guest: " + s.getGuest();
String deleteMessage = "Room ID: " + roomID + " Room Type: " + s.getRoomType() + " Guest: " + s.getGuest();
//int r = JOptionPane.showOptionDialog,null("Are you sure you would like to delete the following \n"
//+ "deleteMessage",
//"Delete a booking",
//JOptionPane.YES_NO_OPTION,
//JOptionPane.QUESTION_MESSAGE,null,null,null);
//if (r == JOptionPane.YES_OPTION) {
// bookings.remove(index);
//}
//if (r == JOptionPane.NO_OPTION){
// return "Booking Was Not Canceled";
// }
int response = JOptionPane.showConfirmDialog(null, deleteMessage, "Confirm Delete",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (response == JOptionPane.NO_OPTION)
{
} else if (response == JOptionPane.YES_OPTION)
{
//bookings.remove(index);
bookings.remove(i);
return deleteMessage + " has been DELETED."; /*I did this.*/
}
}
}
return " Cannot find room";
}
Moreover, after this
bookings.remove(i);
You forgot to return something like
return deleteMessage + " has been DELETED."; /*I did this.*/
Since you failed to return a String on successful completion, that's the reason why it returns "Cannot find room.", even after successful deletion.
Rest of the code is perfect.
Hope that might solve your query.
Regards