I first want to validate that the user entered a value and to make sure to exit if 'cancel' was pushed. Then, I want to validate that the String releaseDateString is in the correct format at the same time as converting the String to java.sql.Date.
The first validation is taking place but then the JOptionPane carries on repeating itself and does not even consider the try and catch following it.
Here is my method
boolean retry = false;
java.sql.Date releaseDate = null;
String releaseDateString = "";
String title = "";
while (!retry) {
while(!retry){//field is validated to make sure a value was entered and to exit if cancel was pushed
releaseDateString = JOptionPane.showInputDialog("Please input the release date of the movie (yyyy-mm-dd)");
qtd.stringValidation(releaseDateString);
}
try { //the date is validated to make sure it is in the correct format
releaseDate = java.sql.Date.valueOf(releaseDateString);
} catch (Exception e) {
retry = false;
JOptionPane.showMessageDialog(null, "Make sure you enter a date in the format of 'dd-mm-yyy'");
}
}
It links to this method
public static boolean stringValidation(String attribute){
boolean retry = false;
if (attribute == null){
System.exit(0);
}
else if (attribute.equals("")) //if the cancel button is selected or no value was entered into the
{
JOptionPane.showMessageDialog(null, "Make sure you enter a character into the textbox");
}
else {
retry = true;
}
return retry;
}
When you do this,
qtd.stringValidation(releaseDateString);
You aren't assigning the result to retry. I believe you wanted,
retry = qtd.stringValidation(releaseDateString);
Related
I am trying out to code a simple arithmetic game in Java but I faced an error like: Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string. This happens when I clicked on number buttons and cleared them to enter a new number but it seems that the string still contains the previous number I clicked. (For example, I clicked 5 and deleted it so I could enter 9 instead and now the string seems to register it as 59 instead of just 9.) I used .setText('') to clear the text area.
This is my code for when the buttons are pressed:
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("one"))
{
answerText.append("1");
userAnswer = userAnswer + "1";
}
// same code for two, three, four... to nine.
if(e.getActionCommand().equals("enter"))
{
int userValue = new Integer(userAnswer);
if (userValue == rightAnswer)
{
score++;
userAnswer = "";
generateRandomProblem();
}
else
{
JOptionPane.showMessageDialog(this,"Wrong answer! Please try again.");
}
}
}
The answer variable and delete button is :
answerText = new JTextArea();
answerText.setEditable(false);
clearbtn = new JButton("Clear");
clearbtn.setActionCommand("clear");
clearAnswer.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
answerText.setText("");
}
});
How do I make sure that my answerText is completely clear?
Your error message:
java.lang.NumberFormatException: For input string
This means that you are trying to parse a string into a number, but the string contains something that cannot be parsed into a number. Java prints the content of the string after the text For input string. In this case there's nothing after that text, because the string that you are trying to parse is the empty string - that you set in the text box by calling answerText.setText("");
Solution: Check if the string you are trying to parse is empty before you try to parse it into a number. For example:
if (e.getActionCommand().equals("enter"))
{
if (!"".equals(userAnswer)) // Check if userAnswer is not empty
{
int userValue = new Integer(userAnswer);
if (userValue == rightAnswer)
{
score++;
userAnswer = "";
generateRandomProblem();
}
else
{
JOptionPane.showMessageDialog(this,"Wrong answer! Please try again.");
}
}
else
{
JOptionPane.showMessageDialog(this, "Please enter a number before pressing Enter.");
}
}
The variable userAnswer doesn't get cleared when answerText is cleared. This might cause issues.
The exception you are having is probably being cause because int userValue = new Integer(userAnswer); is called at a point where userAnswer is empty (because it can't make a number out of nothing).
This question already has answers here:
If statement gives condition is always true
(4 answers)
Closed 2 years ago.
I'm totally new to Java programming and I'm trying to create a Java FX project. I've followed tutorials about the date validation method but it seems to fail.In this certain part I have to make a list with objects inserted by a user in text fields. That includes a date but it needs to be valid.
Below in this piece of code, the object I need to get validated is datep . I've created a method in which if the string is valid, it should set my flag to true and return it. Before the list is created I inserted an if statement to check whether that my flag is set to true which means that the date is verified according to the format.When I run it,it creates the list whatsoever even if the date is invalid.Am I putting the if statement in the wrong part? Cause I think the method is fine.
#Override
public void handle(MouseEvent event) {
if (event.getSource() == NewrentBtn) {
String vehiclen =OximaTxT.getText();
String clientn = ClientTxT.getText();
String store = StoreTxT.getText();
String storer = StorerTxT.getText();
String timerp = TimeTxT.getText();
String timer = TimerTxT.getText();
String datep = DateTxT.getText(); // <-------------
String dater = DaterTxT.getText();
Integer sum = Integer.parseInt(SumTxT.getText());
if(flag = true) { // <------------
createRental(id, vehiclen, store, datep, timerp, clientn, storer, dater, timer, sum);
clearTextFields();
}
}
public boolean Checkdate(String datep) { // <-------------
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date BOD = null;
df.setLenient(false);
try
{
BOD = df.parse(datep); // <----------------
flag = true;
}
catch(Exception e)
{
flag = false;
}
return flag;
}
public void createRental(int id,String vehiclen,String store,String datep,String timerp,String clientn,String storer,String dater,String timer,int sum ) {
Rental m = new Rental(id,vehiclen,store,datep,timerp,clientn,storer,dater,timer,sum);
RentalList.add(m);
rentalTableView.getItems().add(m);
}
From the looks of what you are trying to achieve here is my suggestion to modify the code.
First of all let me explain to you two issues i found: the first one is that you are missing the call to the validation method of the Date, that is the call to the CheckDate(datep) when you receive the text input and store the flag variable, or so it seems as we dont have the full code (which is ok ); and second you are missing a =in the if(flag = true), it should be if(flag == true)
So here is the full code:
#Override
public void handle(MouseEvent event) {
if (event.getSource() == NewrentBtn) {
String vehiclen =OximaTxT.getText();
String clientn = ClientTxT.getText();
String store = StoreTxT.getText();
String storer = StorerTxT.getText();
String timerp = TimeTxT.getText();
String timer = TimerTxT.getText();
String dater = DaterTxT.getText();
Integer sum = Integer.parseInt(SumTxT.getText());
String datep = DateTxT.getText();
boolean flag = Checkdate(datep);
if(flag == true) {
createRental(id,vehiclen,store,datep,timerp,clientn,storer,dater,timer,sum);
clearTextFields();
}
}
}
This way you are verifying if the date is correctly formatted and continue the process if it is according to your scheme.
Finally i have three recommendations as you are new to java programming:
For all methods the first letter should always be in lowercase like public boolean checkDate() this way you can differentiate a method from a Class, which will always start in Uppercase like public class Product. The only exception for this is the constructor of a class.
You should never mix the graphical interface logic, with the logical processing logic. This is: you should keep the processing part in one package and the graphic component in another and relate both of them by creating an instance of the processing logic in the graphical interface.
The user input validation should be directly made in the handler method with try-catch clauses like the following.
Here:
public void handle(MouseEvent event) {
if (event.getSource() == NewrentBtn) {
String vehiclen =OximaTxT.getText();
String clientn = ClientTxT.getText();
String store = StoreTxT.getText();
String storer = StorerTxT.getText();
String timerp = TimeTxT.getText();
String timer = TimerTxT.getText();
String dater = DaterTxT.getText();
Integer sum = Integer.parseInt(SumTxT.getText());
try {
String datep = DateTxT.getText();
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
df.parse(date);
createRental(id,vehiclen,store,datep,timerp,clientn,storer,dater,timer,sum);
clearTextFields();
} catch (ParseException e) {
/* Here you handle what happens when if fails, you can create a JDialog to show
the error or create an alert, whatever you need */
e.printStackTrace();
}
}
}
And voila a cleaner version
So there is this certain part of my program where I can create an account and the created account will be inserted into my database. And I'm trying to code something where *refer to the code:
public void actionPerformed(ActionEvent e) {
String user = userField.getText().trim();
String pass = passField.getText().trim();
String conPass = confirmPass.getText().trim();
try{
// TODO Auto-generated method stub
if(e.getSource()==submit){
if (user.equals(user)&&pass.length()==0){
JOptionPane.showMessageDialog(null, "Fill in the empty field!");
}//check if the pass field is blank
else if(user.length()<5){
JOptionPane.showMessageDialog(null,"Username must be at least 5 characters!");
}
else if(user.equals(user)&&pass.equals(conPass)&&pass.length()!=0){
String sqlLogin = "insert into tblLogin (username,pssword) values ('"+user+"','"+pass+"')";;
getQuery(sqlLogin);
JOptionPane.showMessageDialog(null, "Account Successfully Created!");
create.dispose();
GUI gui = new GUI();
}//if(pass.equals(conPass))
else if(user.length()==0&&pass.length()==0){
JOptionPane.showMessageDialog(null, "Fill in the empty field!");
}//check if both fields are blank
else if (user.length()==0 &&pass.equals(pass)){
JOptionPane.showMessageDialog(null, "Fill in the empty field!");
}//check if user field is blank
else if(user.equals(user)&&pass!=conPass){
JOptionPane.showMessageDialog(null, "Password do not match!");
}//check if password and confirm pass matches
}
I dont really know how to say the problem but look in the if and else if statements, if the user meet one the those conditions, the program should print the JOptionPane thing. Except for the second else if.
You might be wondering why I put these codes at my else if
else if(user.equals(user)&&pass.equals(conPass)&&pass.length()!=0){
String sqlLogin = "insert into tblLogin (username,pssword) values ('"+user+"','"+pass+"')";;
getQuery(sqlLogin);
JOptionPane.showMessageDialog(null, "Account Successfully Created!");
create.dispose();
The reason for this is that, my program is having some logic error when I try to put it in if statement. Please help me with my code thanks :) Feel free to write a new code for me :DD
i might try something like this:
public static boolean isSet(String s){
if(s==null || "".equals(s)) return false;
return true;
}
//.... your validation here
if(isSet(user) && isSet(pass) && isSet(conPass) && pass.equals(conPass)){
//create account
}else{
//smth wrong eg. if(!pass.equals(conPass) { //wrongpass }
}
My code:
name = jTextFieldName.getText();
admin = Integer.parseInt(jTextFieldAdmin.getText());
anal = Integer.parseInt(jTextFieldAnalytical.getText());
creat = Integer.parseInt(jTextFieldCreative.getText());
finish = Integer.parseInt(jTextFieldFinisher.getText());
persons.addPerson(name, admin, anal, creat, finish);
persons.savePersons();
I want to make sure that name is a string and that admin, anal, creat and finish are ints between 0 and 30. I'm thinking that I should use try-catch, but I don't know exactly how to use it in this context. Any help appreciated!
try catch isn't a bad way to handle this:
try {
name = jTextFieldName.getText();
admin = Integer.parseInt(jTextFieldAdmin.getText());
anal = Integer.parseInt(jTextFieldAnalytical.getText());
creat = Integer.parseInt(jTextFieldCreative.getText());
finish = Integer.parseInt(jTextFieldFinisher.getText());
persons.addPerson(name, admin, anal, creat, finish);
persons.savePersons();
} catch (NumberFormatException e) {
// One of the integer fields failed to parse. Do something to alert the user.
}
You can then also put some bounds checking in the try part. e.g.
if (admin < 0 || admin > 30) {
// Problem. Alert the user.
}
Why don't you use a JSpinner instead.
What you need is if-else which statisfies condition or ask user to input again if required.
ex -
if(admin<0 || admin>30){
// ask user to input again.
}
Use InputVerifier for JTextField, like below
public class MyInputVerifier extends InputVerifier {
#Override
public boolean verify(JComponent input) {
String text = ((JTextField) input).getText();
// Validate input here, like check int by try to parse it using Integer.parseInt(text), and return true or false
}
}
// Set input verifier to the text field
jTextField.setInputVerifier(new MyInputVerifier());
I'm creating a method to take an input by a user and validate it to make sure it's correct. If it's correct it will call a method and input the user input in to it. But for some reason, the method call is not working. It doesn't produce any errors, it just simply doesn't do it. I placed a print statement at the end of the code to make sure it actually reaches there and it does, but for some reason it's just not calling the method like it's supposed to. The other method works fine if I call it by itself and input a string via the parameters.
The code is:
public void getGetScheduledShowByFilmInput()////new - omar////
{
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(System.in));
String filmInput;
filmInput = "";
boolean foundFilm;
foundFilm = false;
System.out.println("Here is a list of films that are currently showing:");
for(Film film : films){
System.out.println(film.getFilmName());
}
System.out.println("");
System.out.println("Please type the film name that you wish to view the corresponding shows for and press enter.");
System.out.println("Type 'exit' and press enter to exit this process.");
while(foundFilm == false){
try{
filmInput = reader.readLine();
}
catch (IOException e){
System.out.println("Error");
}
//If user enters "exit" then return.
if(filmInput.equals("exit")){
return;
}
//Check to see if the film name input by the user corresponds to any film showing.
for(Film film : films){
if(film.getFilmName() == filmInput){
foundFilm = true;
break;
}
}
if(foundFilm = true){
System.out.println("Film found.");
}
else{
System.out.println("The film name you entered has not been recognised. Please try again.");
}
}
//Call the function and input the film name input by the user.
getScheduledShowsByFilm(filmInput); ////This is the code that seems to be the problem.
System.out.println("reached bottom");
}
and the second method is:
public void getScheduledShowsByFilm(String inputFilmName)
{
ArrayList<Show> scheduledShows;
scheduledShows = new ArrayList<Show>();
for(Film film : films){
if(inputFilmName == film.getFilmName()){
for(Schedule schedule : schedules){
scheduledShows.add(schedule.getShowsOfFilm(film));
if(scheduledShows.get(scheduledShows.size() - 1) == null){
scheduledShows.remove(scheduledShows.size() - 1);
}
}
}
}
for(Show show : scheduledShows){
System.out.println("**********************************");
show.getShowDetails();
System.out.println("**********************************");
}
}
The second method works perfectly when I call it on its own and enter parameters manually though.
It's probably something extremely simple that I'm not understanding! haha, thank you for your help :)
foundFilm can never be false because you always assign true to it:
if(foundFilm = true){
System.out.println("Film found.");
}
try changing it to this:
if(foundFilm)
{
System.out.println("Film found.");
}
In getGetScheduledShowByFilmInput() and getScheduledShowsByFilm(String) avoid doing string comparison using the equality operator (==). The == operator tests for object equality, but you want to test whether two strings contain the same sequence of characters. Therefore, use equals instead:
//Check to see if the film name input by the user corresponds to any film showing.
for(Film film : films){
if(film.getFilmName().equals(filmInput)){
foundFilm = true;
break;
}
}
and
for(Film film : films){
if(inputFilmName.equals(film.getFilmName())){
for(Schedule schedule : schedules){
scheduledShows.add(schedule.getShowsOfFilm(film));
if(scheduledShows.get(scheduledShows.size() - 1) == null){
scheduledShows.remove(scheduledShows.size() - 1);
}
}
}
}