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());
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
name = full_name_input.getText();
Fname = father_name_input.getText();
cnic = father_cnic_input.getText();
DOB = Integer.parseInt(DOB_input.getText());
Class_V = Integer.parseInt(class_input.getText());
prsnt_add = present_add_input.getText();
city = city_input.getText();
province = radio_text;
if(name.equals("") || Fname.equals("") || cnic.equals("") || DOB==0 || Class_V==0 || prsnt_add.equals("") || city.equals("") || province.equals(""))
{
Toolkit.getDefaultToolkit().beep();
JOptionPane.showMessageDialog(null, "Please fill all fields ! \n");
}
radio_text here is actually input from radio button and it is giving an error
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
actually i want to ensure that none of the jfields remain empty by the user
and if any field remains undefined it shows a popup please fill all fields
but when date of birth or class field or both remain unfiilled by the user it gives an error mentioned in the preeceding paragraph
What's happening is you're checking your fields after you try to set them, but the error occurs before that. For example, if DOB_input's text is "", DOB will throw an error trying to parse that (Integer.parseInt() can't deal with strings like that) before you see that it's empty. If you want to keep your if-statement, you'll have to move it above the lines where you set your values. However, to do that you'd need to tweak it a bit so you check the jfields' values. Like:
if(full_name_input.getText().equals("") || father_name_input.getText().equals("") ..... )
{
Toolkit.getDefaultToolkit().beep();
JOptionPane.showMessageDialog(null, "Please fill all fields ! \n");
}
I bet you have a problem here:
DOB = Integer.parseInt(DOB_input.getText());
Class_V = Integer.parseInt(class_input.getText());
Either DOB_input or class_input (or even both of them) getText() returns empty string. You should catch that exception and properly handle it like this:
try {
value = Integer.parseInt(input.getText());
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Illegal nuber format for field <field>");
return;
}
There is a problem with parsing number from String.
Did you check on which line this happened?
I suppose that here:
DOB = Integer.parseInt(DOB_input.getText());
Class_V = Integer.parseInt(class_input.getText());
I have a task to do which involves asking the user to input their last name and giving the user an account number to login to the program. I have listed the steps below which might make more sense.
1) User creates an account
2) User enters their last name (Stores into the arraylist)
3) User is given an account number (Stores into the arraylist)
4) User can then login using their last name and account number (checks arraylist for lastname and accountnumber, if it matches then login message, if it doesnt then error message)
A user enters their last name and they are given an account number which they then use to login to deposit, withdraw and check balance.
How do i create a programe to do this without the use of database?
Account Class
private static int number = 500;
Account(){
accountNumber = number++;
}
Create Account
public void createAccount(){
String firstName;
System.out.print("Please Enter Last Name: ");
lastName = scanner.nextLine();
System.out.println("This is your Account Number to log into: " + _______ );
}
public void logIn(){
System.out.println("Please enter your last name: ");
System.out.println("Please enter your account number: ");
}
I would like to suggest another method using xml to store credentials follow the steps below
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
string username;
string pwd;
string CurrentUser = "";
string CurrentPwd = "";
bool LoginStatus = false;
username = Login1.UserName;
pwd = Login1.Password;
XmlDocument xmxdoc = new XmlDocument();
xmxdoc.Load(Server.MapPath("Register.xml"));
XmlNodeList xmlnodelist = xmxdoc.GetElementsByTagName("user");
foreach (XmlNode xn in xmlnodelist)
{
XmlNodeList xmlnl = xn.ChildNodes;
foreach (XmlNode xmln in xmlnl)
{
if (xmln.Name == "Name")
{
if (xmln.InnerText == username)
{
CurrentUser = username;
}
}
if (xmln.Name == "Password")
{
if (xmln.InnerText == pwd)
{
CurrentPwd = pwd;
}
}
}
if ((CurrentUser != "") & (CurrentPwd != ""))
{
LoginStatus = true;
}
}
if (LoginStatus == true)
{
Session["UserAuthentication"] = username;
Session.Timeout = 1;
Response.Redirect("welcome.aspx");
}
else
{
Session["UserAuthentication"] = "";
}
}
in your xml file
<user>
<Name>smashcode</Name>
<Password>smashcode</Password>
</user>
I guess this would be better approach than a arraylist approach
if you want to try in using arraylist follow steps
step1:username_list{uesr1,user2,user3}
password_List{pass1,pass2,pass3}
step:check all entries with entered userid and password in a loop as follows
int flag = 0;
while(username_list.get(i)!=null)
{
if((username_list.get(i).equals(enteredusername))&&((password_list.get(i).equals(enteredpassword)))
{
flag = 1;
}
}
if(flag==1)
{
System.out.println("login successful ");
Response.Redirect("welcome.aspx");
}
I had written second code implementation in cut short
Hope my work will be helpful.Keep coding
Not a full answer here but a few suggestions....
You could create a "bank" class... It might hold the arraylist of accounts, also holding
createAccount()
delAccount()
findAccount()...
So on and so forth
Having posted this I now see it is an answer, my bad guys
I assume you need to be able to keep this information after the execution is complete, which means you need to store the information somewhere besides the running program.
Of the top of my head, you can use a file to store this store of information, where each line of the file would equal a match of last name - account. When opening the program, you read the file. Try reading:
http://www.tutorialspoint.com/java/java_files_io.htm or
https://docs.oracle.com/javase/tutorial/essential/io/file.html
The solution is similar to using a database, so I don't know if it will do or not. Hope it does.
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);