I have tried many methods but still did not works. I tried to catch if there is a number in JTextfield it will make the string text turn to red and pop up the JOption. But my code only catches if there are numbers in both of my JTextfield. I want to my JTextField have only characters and space.
(jtf2 and jtf3 are JTextField)
if(ae.getSource() == bcreate) // create
{
String firstname;
String lastname;
String id;
firstname = jtf2.getText();
lastname = jtf3.getText();
try
{
Integer.parseInt(jtf2.getText());
jtf2.setForeground(Color.RED);
Integer.parseInt(jtf3.getText());
jtf3.setForeground(Color.RED);
JOptionPane.showMessageDialog(null, "Please enter valid character","ERROR",JOptionPane.ERROR_MESSAGE);
}
catch(NumberFormatException w)
{
create(firstname, lastname);
jtf3.setForeground(Color.black);
jtf2.setForeground(Color.black);
id = Integer.toString(e.length);
current = Integer.parseInt(id);
jta.setText("Employee #" + id + " " + firstname + " " + lastname + " was created.");
}
}
This not the correct way to check for numbers in code. Exception is for exception condition. And here we are exploiting it and running main code in exception. Rather you should use regex to check if, text contains any number or not. As below :
String firstname = jtf2.getText();
String lastname = jtf3.getText();
String id;
boolean isInvalidText = false;
if(firstname.matches(".*\\d.*")) {
jtf2.setForeground(Color.RED);
isInvalidText = true;
}
if(lastname.matches(".*\\d.*")) {
jtf3.setForeground(Color.RED);
isInvalidText = true;
}
if(isInvalidText) {
JOptionPane.showMessageDialog(null, "Please enter valid character","ERROR",JOptionPane.ERROR_MESSAGE);
} else {
create(firstname, lastname);
jtf3.setForeground(Color.black);
jtf2.setForeground(Color.black);
id = Integer.toString(e.length);
current = Integer.parseInt(id);
jta.setText("Employee #" + id + " " + firstname + " " + lastname + " was created.");
}
Related
I am making an java program for college and I am stuck at one point, the exam says I need to extract information from an txt file that is already written. I need to get only the information from the end of the lines like password or something.
DISCLAIMER:
I know how to do it by using scanner and file. But it is not really clear how to extract only the information not the whole line.
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
public class Trip {
private String password;
private String placeOfDeparture;
private String destination;
private int durationInDays;
private double wage;
private double rentPrice;
private String firstName;
private String lastName;
private String[] passwords;
public Trip(String placeOfDeparture, String destination, int durationInDays, double wage,
double rentPrice, String firstName, String lastName) {
super();
this.placeOfDeparture = placeOfDeparture;
this.destination = destination;
this.durationInDays = durationInDays;
this.wage = wage;
this.rentPrice = rentPrice;
this.firstName = firstName;
this.lastName = lastName;
generateTripPassword();
}
public void generateTripPassword() {
Random rand = new Random();
int randomNumbers = rand.nextInt(100);
String personInitials = "";
String departureInitials = "";
String destinationInitials = "";
personInitials += firstName.substring(0, 1).toUpperCase();
personInitials += lastName.substring(0, 1).toUpperCase();
departureInitials += placeOfDeparture.substring(0, 2).toUpperCase();
destinationInitials += destination.substring(0, 2).toUpperCase();
for(int i = 0; i < passwords.length; i++) {
if(passwords[i] == null) {
passwords[i] = personInitials + departureInitials + destinationInitials + randomNumbers;
break;
}
}
this.password = personInitials + departureInitials + destinationInitials + randomNumbers;
}
public void getTripInformation() {
System.out.println("Trip details: \n");
System.out.println("Trip password: " + password);
System.out.println("Passenger name: " + firstName + " " + lastName + ".");
System.out.println("Duration in days: " + durationInDays + ".");
System.out.println("Wage: " + wage + ".");
System.out.println("Rent price is: " + rentPrice + ".");
}
public void writeTripInfo(String tripType) {
File file = new File(this.password + ".txt");
try {
FileWriter trip = new FileWriter(file);
trip.write("Trip details: ");
trip.write("Trip password: " + password);
trip.write("Passenger name: " + firstName + " " + lastName + ".");
trip.write("Duration in days: " + durationInDays + ".");
trip.write("Wage: " + wage + ".");
trip.write("Rent price is: " + rentPrice + ".");
trip.write("Type of the trip is: " + tripType);
trip.close();
System.out.println("File writing successfully completed! Name of yje file is: " + this.password + " . Enjoy.");
} catch (IOException e) {
System.out.println("An error occured while writing file.");
System.out.println("Here is the error debug code: ");
e.printStackTrace();
}
}
}
After you have put each part on its own line (and removed the '.' at the end), you can parse each line by splitting on ':'
public void readTripInfo(String path)
{
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
String line;
// Read each line of file
while ((line = br.readLine()) != null) {
// Split on ':'
String [] parts = line.split(":");
if (parts.length == 2) {
// Save
if (parts[0].equals("Trip password")) {
password = parts[1].trim();
}
else if (parts[0].equals("Passenger name")) {
String [] names = parts[1].trim().split(" ");
if (names.length == 2) {
firstName = names[0];
lastName = names[1];
}
}
else if (parts[0].equals("Duration in days")) {
durationInDays = Integer.parseInt(parts[1].trim());
}
// Continue for the rest
}
}
}
catch (Exception e) {
System.out.println(e);
}
}
I have a GUI based e-store project. I read in a file and parse through it and saved it into an array.
The file format is like so: 11111, "title", 9.90
11111 is the book id, "title" is title, and 9.90 is the price.
I currently have 3 classes in my project. 1 class for Input/Output, 1 class for the Book store GUI code, and another for pop-up boxes when specific buttons are clicked.
In the GUI code, I check read the file into String[] fileArray and then loop through it until there is a match (with TextField input String bookIds = bookIdinput.getText())
I'm able to successfully get a match and go on with the rest of the code, but when there isn't a match, I get an error: Exception in thread "JavaFX Application Thread" java.lang.NullPointerException at windowDisplay.lambda$start$3(windowDisplay.java:###)
which is this line of code for(int i=0; i<fileArray.length; i++)
If there isn't a match, then it should show a pop-up box saying that bookID isn't found.
Below is some of the GUI code
public class windowDisplay extends Application
{
// Variable declarations
private String[] fileArray = null;
private String holdStr = "";
private Stage mainWindow;
private boolean matchFound = false;
private int count = 1;
private int lineItems = 1;
private double totalAmount = 0.0;
private double subTotal = 0.0;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception
{
// OMITTED CODE
// These TextFields show the output depending on the input TextField's.
itemInfoOutput.setDisable(true);
orderSubtotalOutput.setDisable(true);
// Process item button.
processItem.setText("Process Item #" + count);
processItem.setMinWidth(106);
processItem.setOnAction(e ->
{
int numItems = Integer.parseInt(numItemInput.getText());
lineItems = numItems;
String bookIDs = bookIdInput.getText();
int qtyItems = Integer.parseInt(qtyItemInput.getText());
// Read file and check for Book ID
fileArray = bookStoreIO.readFile(bookIDs);
// Loop through array to find match or no matches
for(int i=0; i<fileArray.length; i++)
{
// If there is a match in book ID
if (fileArray[i].equals(bookIDs))
{
double price = Double.parseDouble(fileArray[i + 2]); // Price is in the i+2 position
double discount = calculateDiscount(qtyItems);
totalAmount = calculatePrice(qtyItems, price);
itemInfoOutput.setText(fileArray[i] + " " + fileArray[i + 1] + " " + "$" + price + " " +
qtyItems + " " + discount + "%" + " " + "$" + df.format(totalAmount));
// Disable processItem Button if there is a match and enable confirmItem Button
processItem.setDisable(true);
confirmItem.setDisable(false);
matchFound = true;
}
}
if(matchFound == false)
System.out.println("No match found!");
});
}
// OMITTED CODE
// This method calculates the discount depending on the quantity of items
public static double calculateDiscount(int inputQty){return null;}
// This methdod calculates the price with the discount
public static double calculatePrice(int inputQty, double price){return null;}
}
This class reads the file and returns an array with the contents of that file (once split by the ", " delimitter).
public class bookStoreIO
{
// This method reads the input file "inventory.txt" and saves it into an array.
public static String[] readFile(String stringIn)
{
try
{
String nextLine;
String[] fIn;
// Read file
BufferedReader br = new BufferedReader(new FileReader("inventory.txt"));
while((nextLine = br.readLine()) != null)
{
fIn = nextLine.split(", "); // Split when ", " is seen
if(stringIn.equalsIgnoreCase(fIn[0]))
{
br.close(); // Close file
return fIn; // Return array
}
}
}
// Just in case file isn't found
catch(IOException e)
{
System.out.println("File not found.");
}
return null;
}
I apologize if this seems messy, I'm still new to JavaFX and Java programming.
If you think more code is needed, please let me know!
EDIT: I improved some variable naming and removed the for loop. I'm still having trouble checking when there isn't a match.
public class windowDisplay extends Application
{
// Variable declarations
private String[] fileArray = null;
private Stage mainWindow;
private boolean matchFound = false;
private int count = 1;
private int lineItems = 1;
private double totalAmount = 0.0;
private double subTotal = 0.0;
private int itemQty = 0;
private int idBook = 0;
private String bookTitle = "";
private double bookPrice = 0.0;
private double discountAmount = 0.0;
private String resultOrder = "";
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception
{
// OMITTED CODE
// These TextFields show the output depending on the input TextField's.
itemInfoOutput.setDisable(true);
orderSubtotalOutput.setDisable(true);
// Process item button.
processItem.setText("Process Item #" + count);
processItem.setMinWidth(106);
processItem.setOnAction(e ->
{
int numItems = Integer.parseInt(numItemInput.getText());
lineItems = numItems;
String bookIDs = bookIdInput.getText();
itemQty = Integer.parseInt(qtyItemInput.getText());
// Read file and check for Book ID
fileArray = bookStoreIO.readFile(bookIDs);
idBook = Integer.parseInt(fileArray[0]);
bookTitle = fileArray[1];
bookPrice = Double.parseDouble(fileArray[2]);
discountAmount = calculateDiscount(itemQty);
totalAmount = calculatePrice(itemQty, bookPrice);
itemInfoOutput.setText(idBook + " " + bookTitle + " $" + bookPrice + " " + itemQty + " " + discountAmount
+ "% $" + df.format(totalAmount));
itemInfo.setText("Item #" + count + " info:");
processItem.setDisable(true);
confirmItem.setDisable(false);
matchFound = true;
if(matchFound == false)
System.out.println("not found");
});
// OMITTED CODE
// This method calculates the discount depending on the quantity of items
public static double calculateDiscount(int inputQty){return null;}
// This method calculates the price with the discount
public static double calculatePrice(int inputQty, double price){return null;}
}
I'm also having trouble saving
itemInfoOutput.setText(idBook + " " + bookTitle + " $" + bookPrice + " " + itemQty + " " + discountAmount
+ "% $" + df.format(totalAmount));
into an String or String array to print out a list of all the corresponding matches (along with their book ID, book Title, book Price, quantity, discount , and total price).
An example is shown below:
enter image description here
EDIT 2: The right box is the main GUI. The bottom left box is what shows up when a wrong book is entered (on the 2nd order). The top left is the length of the array.
// Process item button.
processItem.setText("Process Item #" + count);
processItem.setMinWidth(106);
processItem.setOnAction(e ->
{
int numItems = Integer.parseInt(numItemInput.getText());
lineItems = numItems;
String bookIDs = bookIdInput.getText();
itemQty = Integer.parseInt(qtyItemInput.getText());
// Read file and check for Book ID
fileArray = bookStoreIO.readFile(bookIDs);
for(int i=0; i<fileArray.length; i++)
System.out.println(fileArray[i]);
if(fileArray.length >= 3)
{
idBook = Integer.parseInt(fileArray[0]);
bookTitle = fileArray[1];
bookPrice = Double.parseDouble(fileArray[2]);
discountAmount = calculateDiscount(itemQty);
totalAmount = calculatePrice(itemQty, bookPrice);
resultOrder = itemInfoOutput.getText();
itemInfoOutput.setText(idBook + " " + bookTitle + " $" + bookPrice + " " + itemQty + " " + discountAmount
+ "% $" + df.format(totalAmount));
resultOrder = idBook + " " + bookTitle + " $" + bookPrice + " " + itemQty + " " + discountAmount
+ "% $" + df.format(totalAmount);
itemInfo.setText("Item #" + count + " info:");
processItem.setDisable(true);
confirmItem.setDisable(false);
}
else
alertBox.confirmDisplay("Book ID " + idBook + " not in file");
});
How do I not store values from the program when it loops back again. For example, if I plan to enter two families, first I will ask for the details of the first family and display their names, and then I want to use the same variables to collect the next family and display their names without having stored information from the previous family.
public static void main(String[] args) {
// TODO code application logic here
String ans;
String res;
double cont;
int cot;
String name;
String order = "";
do {
ans = JOptionPane.showInputDialog(null,"What is the name of the "
+ "family?" );
res = JOptionPane.showInputDialog(null, "How many member in the " + ans +
" family?");
cot = Integer.parseInt(res); // Converts res String to a number
for (int count = 1; count < cot; count ++) {
name = JOptionPane.showInputDialog(null, " Enter first name: " + count);
order += name + " " + ans + "\n";
}
JOptionPane.showMessageDialog(null, "Members of the " + ans
+ " Family" + "\n" + order);
cont = JOptionPane.showConfirmDialog(null, "Do you want to add another "
+ "family", "Membership", JOptionPane.YES_NO_OPTION);
}while (cont == JOptionPane.YES_OPTION);
if (cont == JOptionPane.NO_OPTION){
JOptionPane.showMessageDialog(null," Come Back Again");
}
}
}
Your order variable is a String that you are adding the names to. Just reset it at the beginning of the loop:
...
do {
order = "";
...
I'm working on this little project, I was given the driver and had to write the helper class for it.
Driver:
public class MyBookDriver {
private static final Scanner KBD = new Scanner(System.in);
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// Constructors
MyBookAccount bbSheldon = new MyBookAccount("Sheldon", true);
MyBookAccount bbPenny = new MyBookAccount("Penny", false);
MyBookAccount bbAmy = new MyBookAccount("Amy", "Montreal", true);
MyBookAccount bbLeonard = new MyBookAccount("Leonard");
System.out.println("\n" + MyBookAccount.getNumAccounts()
+ " MyBook accounts have been created.");
// Mybook ID
System.out.println("\nMyBook Accounts:");
System.out.println(" Sheldon's ID: " + bbSheldon.ID);
System.out.println(" Penny's ID: " + bbPenny.ID);
System.out.println(" Amy's ID: " + bbAmy.ID);
System.out.println(" Leonard's ID: " + bbLeonard.ID);
pause();
// logged in
System.out.println("\nMyBook Accounts:");
System.out.println(" Sheldon is "
+ (bbSheldon.isLoggedIn() ? "" : "not ") + "logged in");
System.out.println(" Penny is "
+ (bbPenny.isLoggedIn() ? "" : "not ") + "logged in");
System.out.println(" Amy is "
+ (bbAmy.isLoggedIn() ? "" : "not ") + "logged in");
System.out.println(" Leonard is "
+ (bbLeonard.isLoggedIn() ? "" : "not ") + "logged in");
pause();
//post a wall message
System.out.println("\nPosting wall update:");
bbSheldon.setWallPost("I like flags!");
bbPenny.setWallPost("Looking for a job.");
bbLeonard.setWallPost("I'm just hoping I can date a girl "
+ "from next door.");
System.out.println(" Sheldon's: " + bbSheldon.getWallPost() + "\n"
+ " Penny's: " + bbPenny.getWallPost() + "\n"
+ " Amy's: " + bbAmy.getWallPost() + "\n"
+ " Leonard's: " + bbLeonard.getWallPost() + "\n");
pause();
//Sending messages
System.out.println("\nSending messages:");
bbLeonard.sendMessage(bbPenny, "Will you go out with me tonight?");
bbAmy.sendMessage(bbSheldon, "Neuroscience is a real science.");
bbPenny.sendMessage(bbAmy, "What a nice picture.");
checkMessages(bbSheldon);
checkMessages(bbPenny);
checkMessages(bbAmy);
checkMessages(bbLeonard);
pause();
//toString
System.out.println("\nDisplaying info:");
System.out.println(bbSheldon);
System.out.println(bbPenny);
System.out.println(bbAmy);
System.out.println(bbLeonard);
pause();
}
private static void checkMessages(MyBookAccount user) {
MyBookAccount aFriend;
aFriend = user.getFriend();
if (aFriend != null) {
System.out.println(" " + user.getName() + "'s message from "
+ aFriend.getName()
+ " is " + user.getMessage());
} else {
System.out.println(" " + user.getName() + " has no messages");
}
}
private static void pause() {
System.out.print("\n...press enter...");
KBD.nextLine();
}
}
And my (messy unfinished) code:
public class MyBookAccount {
public final int MAX_CHAR = 20;
public final int ID;
public static int nextId = 1;
private String name;
private String location;
private Boolean loggedIn;
private String wallPost = "(none)";
private String latestMessage = "(none)";
private MyBookAccount friend = null;
private static int numberOfAccounts = 0;
MyBookAccount(String n, String l, Boolean i) {
name = n;
location = l;
loggedIn = i;
ID = nextId;
nextId++;
numberOfAccounts++;
}
MyBookAccount(String n, Boolean i) {
name = n;
location = "Halifax";
loggedIn = i;
ID = nextId;
nextId++;
numberOfAccounts++;
}
MyBookAccount(String n) {
name = n;
location = "Halifax";
loggedIn = false;
ID = nextId;
nextId++;
numberOfAccounts++;
}
public static int getNumAccounts() {
return numberOfAccounts;
}
public void setLoggedIn(boolean log) {
loggedIn = !log;
}
boolean isLoggedIn() {
return loggedIn;
}
public void setWallPost(String newPost) {
if (newPost.length() > MAX_CHAR) {
System.out.println("Cannot update wall post for " + name
+ ". Post must be 20 characters or less.");
} else {
wallPost = newPost;
}
}
public String getWallPost() {
return wallPost;
}
public String getMessage() {
return this.latestMessage;
}
public void sendMessage(MyBookAccount to, String message) {
friend = to;
if (to.loggedIn != true) {
System.out.println("Could not post message from " + name
+ ". " + to.name + " is not logged in!");
latestMessage = "(none)";
} else if (to.loggedIn == true) {
latestMessage = message;
}
}
public MyBookAccount getFriend() {
return friend;
}
public void setName(String n) {
name = n;
}
public String getName() {
return name;
}
public void setLocation(String location) {
this.location = location;
}
public String getLocation() {
return location;
}
#Override
public String toString() {
if (friend == null) {
return "MyBookAccount #" + ID + "{\n "
+ name + " in " + location + "\n "
+ "About me: " + wallPost + "\n "
+ "Logged In:" + loggedIn + "\n ";
} else {
return "MyBookAccount #" + ID + "{\n "
+ name + " in " + location + "\n "
+ "About me: " + wallPost + "\n "
+ "Logged In:" + loggedIn + "\n "
+ "Message from " + friend.name + ": "
+ latestMessage + ".\n";
}
}
}
I just can't figure out one thing.
In the messages part, I' getting the from and to people mixed up.
For example; It should say
Sending messages:
Could not post message from Leonard. Penny is not logged in!
Sheldon's message from Amy is Neuroscience is a real science.
Penny has no messages
Amy's message from Penny is What a nice picture.
Leonard has no messages
and I get:
Sending messages:
Could not post message from Leonard. Penny is not logged in!
Sheldon has no messages
Penny's message from Amy is What a nice picture.
Amy's message from Sheldon is Neuroscience is a real science.
Leonard has no messages
Any ideas on how to remedy this?
Thanks a bundle.
I'm not trying to debug your code here, but let me just make a remark on this:
public void sendMessage(MyBookAccount to, String message) {
friend = to;
if (to.loggedIn != true) {
System.out.println("Could not post message from " + name
+ ". " + to.name + " is not logged in!");
latestMessage = "(none)";
} else if (to.loggedIn == true) {
latestMessage = message;
}
}
This code smells, because it will not send any message, but just alter the state of this (the sender's) object ( friend = to, latestMessage = ...). Plus it checks the conditions of the receiver, while the message should just send a message and react on any bad outcome. Rather imagine something like this:
class MyBookAccount {
//....
public void sendMessage(MyBookAccount receiver, String message) {
try{
receiver.accept(this, message);
}catch(MessageRejectedException e){
//maybe put in queue to try again later, or log the date, time and reason of failure.
}
}
}
where:
class MyBookAccount {
private final List<String> receivedMessages = new ArrayList<>();
...
public void accept(MyBookAccount sender, String message){
if(!loggedIn){
throw new MessageRejectedException("not online");
}
receivedMessages.add(message);
//you can also have a list of Objects that are like
//class Message{String senderName; String message; Date reveived; /*...*/}
//trigger UI update or fire property changed event that announces the list of messages has changed
}
public Optional<String> getLastMessage(){
return receivedMessages.isEmpty() ? Optional.empty()
: Optional.of(receivedMessages.get(receivedMessages.size()-1));
}
This way the receiver of the message has full control over the conditions that it needs to receive a message, or how many messages it likes to keep, or if it likes to record a date with the message (when the message was received). The sender does not care, whether the receiver is just a proxy, the receiver itself or what conditions have to be met to send the message, it just has to handle the possible error conditions (which can be many) - and it is free to ignore or log them as well.
I think that the start of the method sendMessage(MyBookAccount to, String message) { got a problem. Since you send a message to someone, the friend should be setted to the receiver ?
So it would rather be:
public void sendMessage(MyBookAccount to, String message) {
to.setFriend(this);
Then in the MyBookAccount you add a method like this:
public void setFriend(MyBookAccount friend) {
this.friend = friend;
}
I'm creating a booking system in Java to prevent double bookings i have created a for loop that should change a Boolean to booked once the booking is made however it is changing all the bookings to booked when i only want one instance of booking so no one else can make a booking.
public static boolean booked;
private void FSubmitActionPerformed(java.awt.event.ActionEvent evt) {
for ( int i = 0; i < Airplane.Fseat.length; i++)
{
String seat = FCol.getSelectedItem().toString() + FRow.getSelectedItem().toString();
String items = Snack.getSelectedItem().toString() + " " + Drink.getSelectedItem().toString();
Airplane.Fseat[i] = seat;
Airplane.item[i] = items;
if (Airplane.Fseat[i] != null)
{
System.out.println("Seat number is First class " + Airplane.Fseat[i].toString() + "\n" +"Food and drink " + " " + Airplane.item[i].toString());
i++;
}
else
{
System.out.println("Cannot book already taken");
}
}
You have not put any condition to check, how a particular seat will be set selected.
So you will need to modify your code as:
for ( int i = 0; i < Airplane.Fseat.length; i++)
{
String seat = FCol.getSelectedItem().toString() + FRow.getSelectedItem().toString();
String items = Snack.getSelectedItem().toString() + " " + Drink.getSelectedItem().toString();
if(your_condition_to_check_if_this_seat_is_selcted ){
Airplane.Fseat[i] = seat;
Airplane.item[i] = items;
}
if (Airplane.Fseat[i] != null)
{
System.out.println("Seat number is First class " + Airplane.Fseat[i].toString() + "\n" +"Food and drink " + " " + Airplane.item[i].toString());
i++;
}
else
{
System.out.println("Cannot book already taken");
}
}