Is it possible, in Java, to include a user's input into an exception message while also using the valuse as an int or double? For example, they should enter a number (e.g., 5) but instead fat-finger something like (5r).
Is it possible to have a message say something like "You entered 5r, but should have entered a number."?
I tried using the traditional way of getting variables to print in Java here:
try {
System.out.println();
System.out.println("Value: ");
double value = sc.nextDouble();sc.nextLine();
exec.ds.push(value);
}
catch (Exception e1) {
System.out.println(e1+ "You entered: " + value + ": You must enter a number");
}
In this case, I am trying to get value displayed in the Exception message, where value is the user's invalid input.
At value it gives the error cannot find symbol.
Below is the answer I came up with. The reason I choose this answer was because most of your answers produced the output, "You entered 0.0 ..." because the answer must first be a string to be printed in the console. In addition, to be used as a number elsewhere in the program the String has cast to an Object of type Double or Integer :
String value = null; //declared variable outside of try/catch block and initialize.
try {
System.out.println();
System.out.println("Value: ");
value = sc.nextLine(); //Accept String as most of you suggested
Double newVal = new Double(value); //convert the String to double for use elsewhere
exec.ds.push(newVal); //doulbe is getting used where it would be a 'number' instead of string
}
catch (Exception e1) {
System.out.println(e1+ "You entered: " + value + ": You must enter a number"); //the String valuse is received and printed as a String here, not a 'number'
} //now prints what the users inputs...
This does not work, because value is no longer in scope in the catch block. Instead you can declare it before the try:
double value = 0;
try {
System.out.println();
System.out.println("Value: ");
value = sc.nextDouble();sc.nextLine();
exec.ds.push(value);
} catch (Exception e1) {
System.out.println(e1+ "You entered: " + value + ": You must enter a number");
}
This will however not help if the exception is thrown because of a syntax error in the double. To handle this, you need to read a String and then convert to a double.
Get user input:
String input = '';
try{
Console console = System.console();
input = console.readLine("Enter input:");
}
... then in your catch you could do:
catch (Exception e1) {
System.out.println(e1+ "You entered: " + input + ": You must enter a number");
}
Other than the above, I don't see what the problem is. You can google how to get user input in Java, and then just take the input, put it in a variable, and print it out on error.
In this case - no, as the calling of sc.nextLine() causes the exception to be thrown, so no value is written to variable value.
Moreover, value is a local variable in this case and is unavailable from other blocks of code.
value it gives the error cannot find symbol.
You have declare the value in local block. And you are trying to access it outside the block.
Is it possible to have a message say something like "You entered 5r, but should have entered an number.
Better option is to use flag variable and loop until user enter correct number.
boolean flag = true;
double value = 0;
while(flag)
{
try {
System.out.println();
System.out.println("Value: ");
value = sc.nextDouble();
exec.ds.push(value);
flag = false;
}
catch (Exception e1) {
System.out.println(e1+ "You entered: " + value + ": You must enter a number");
}
}
According to the documentation nextDouble():
Scans the next token of the input as a double. This method will throw InputMismatchException if the next token cannot be translated into a valid double value.
So, if the input cannot be translated into a double, an exception is thrown. If you want to provide the inputted string in the exception message, I suggest you read the line as a string and try to parse it to a double, and if that fails, you can include the read line in the exception message.
Related
I am pretty new to Java and I am doing this project. I keep getting the following error message while I click a jButton (submitButton) in the runtime, and I am not sure why as it is not telling which line the problem is at.
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
Below is my code, I was wondering if anybody could help? Maybe help me find the error, or tell me what the error message means. Thank you!
private void submitButtonActionPerformed(java.awt.event.ActionEvent evt) {
String fullName = nameText.getText();
String email = emailText.getText();
String address = addressText.getText();
String phoneNumber = phoneText.getText();
// sets either true or false to membershipSelected if a plan is selected
boolean membershipSelected = standardMembership.isSelected() || silverMembership.isSelected() || goldMembership.isSelected();
double total = 0;
// checks if the text entered in phone number text field can be parsed to an integer
// this is only possible if it is a number, if it is a string, then error pop-up appears
try {
int phone = Integer.parseInt(phoneText.getText());
}
catch(Exception e) {
javax.swing.JOptionPane.showMessageDialog(keepStrongMain.this, "This is not a valid phone number, please try again!");
}
// checks if email text field does not contain "#" or a domain
if(!email.contains("#") || !email.contains(".com") && !email.contains(".de") && !email.contains(".co.uk")){
javax.swing.JOptionPane.showMessageDialog(keepStrongMain.this, "This is not a valid email address, please try again!");
}
else {
CardLayout card =(CardLayout)mainPanel.getLayout();
card.show(mainPanel, "card3");
}
// checks if length of phone number is 11, if not shows error pop-up
int phoneLength = Integer.parseInt(phoneText.getText());
if(phoneLength != 11){
javax.swing.JOptionPane.showMessageDialog(keepStrongMain.this, "This phone number is not long enough, please try again!");
}
else {
CardLayout card =(CardLayout)mainPanel.getLayout();
card.show(mainPanel, "card3");
}
// checks if a plan is selected, if not shows error pop-up
if(membershipSelected){
CardLayout card =(CardLayout)mainPanel.getLayout();
card.show(mainPanel, "card3");
}
else {
javax.swing.JOptionPane.showMessageDialog(keepStrongMain.this, "Please select a membership!");
}
// sets the final overview to an empty string that can be added to with selections later
String overview = "";
if (standardMembership.isSelected()){
overview = overview + " " + standardMembership.getText() + '\n';
total = 200;
}
if (silverMembership.isSelected()){
overview = overview + " " + silverMembership.getText() + '\n';
total = 450;
}
if (goldMembership.isSelected()){
overview = overview + " " + goldMembership.getText() + '\n';
total = 600;
}
}
You have two places where you perform Integer.parseInt(phoneText.getText());
At the first time, the parsing is surrounded by a try-catch block and that handles the NumberFormatException that would be thrown in case phoneText.getText() is empty or not a number.
The second time, the parsing is not surrounded by any try-catch. This time the NumberFormatException thrown is unhandled and hence you are seeing the Exception.
You should ideally parse the phoneText.getText() once and have your conditions modified accordingly.
I'm trying to get this to loop back to the input if the input is invalid.
if(userSelection == 'G') {
String genderPrompt = "Please enter animal's gender\n" + "Male\n" + "Female";
System.out.println(genderPrompt);
String animalGender = readInput.nextLine().toLowerCase();
System.out.println(animalGender);
while(!animalGender.equals("male") && !animalGender.equals("female")) {
System.out.println("Invalid Selection.");
System.out.println(genderPrompt);
}
animal.setGender(animalGender);
System.out.println("Animal Gender has been set to " + animal.getGender());
Remember that when you create a while loop, you need to edit or update the variable so that the condition will eventually become false, otherwise the loop will continue infinitely.
Since your while loop runs depending on the value of animalGender, it would make sense to update animalGender by taking in user input inside the while loop. By doing this, if the user's animalGender is invalid, we output that there is an error and ask them for another input:
while (!animalGender.equals("male") && !animalGender.equals("female")) {
System.out.println("Invalid Selection.");
System.out.println(genderPrompt);
animalGender = readInput.nextLine().toLowerCase();
}
Try this.
if (userSelection.equals("G")) {
String animalGender;
do {
String genderPrompt = "Please enter animal's gender \nMale \nFemale";
System.out.println(genderPrompt);
animalGender = sc.next().toLowerCase();
} while (!animalGender.equals("male") && !animalGender.equals("female"));
animal.setGender(animalGender);
System.out.println("Animal Gender has been set to " + animal.getGender());
}
I have a really big program that needs to check what character is typed this is just a part of the broken part. So it worked when I had it logging each character typed. But when I try to add each character to the string so when they type the word hi it looks like this:
hi
and NOT
h
i
No matter what i try it either gives me the first value typed and doesnt add each character to the string I also want it to print out the string every 5 seconds im not sure if I did that right either but it might be correct.
String log = " ";
if(event.getVirtualKeyCode() == GlobalKeyEvent.VK_SPACE){
log = log + "";
}
if(event.getVirtualKeyCode() == GlobalKeyEvent.VK_BACK){
log = log + "[BACKSPACE]";
}
String timestamp = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss").format(Calendar.getInstance().getTime());
while(true){
try {
Thread.sleep(5000);
System.out.println("[" + timestamp + "]" + log);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
Try to declare a new string:
String log = new String(" ");
here is my situation. I have a project that I am doing. I'm using netbeans 8.0.2 IDE java language. Here is my code:
try{
memdt = request.getParameter("member date");
if(!memdt.isEmpty()){
n.setMemdt(memdt);
}else{
msg += "Member date field is empty<br>";
}
} catch (Exception e){
msg += "Member date error: " + e.getMessage() + "<br>";
}
That code is fine but what I want to do now is validate using the try catch method for password and that is a long character. Does anyone know how to do that? Thank you.
Judging by the title of your question, you are trying to do something like this:
try {
Long.parseLong(memdt);
} catch(NumberFormatException nfe) {
msg += "Member date error: not a number";
}
NumberFormatException it's what the Number classes generally throw when a string can not be parsed. The result of Long.parseLong() is discarded since the long value it returns is irrelevant, the test just checks that the parsing can be done.
Problem solved.
I have two methods in my class.
private void retrieveDetails(){
List<String> details = File.getCredentials();
username = details.get(0);
pw = details.get(1);
}
private void checkCredentials() throws IOException {
retrieveDetails();
System.out.println("\nPlease enter USERNAME: ");
String usersName = scan.next();
System.out.println("\nPlease enter PASSWORD: ");
String usersPW = scan.next();
System.out.println("\nEntered details: " + usersName + ", " + usersPW);
System.out.println("\nSystems details: " + userName + ", " + pw);
if (usersName.equals(username) && usersPW.equals(pw)) {
doWork();
} else {
System.out.println("Incorrect credentials");
}
}
I thought I came up with a solution by moving the following up to where my strings are initialized.
List<String> creds = File.getCredentials();
I created a System.out statement to check if the details coming from retrieveDetails() match those entered by the users. They do match - but when the system goes to the else clause instead of executing doWork();
If what is printed is the same then try trimming before comparing. E.g.:
if (usersName.trim().equals(username.trim()) && usersPW.trim().equals(pw.trim())) {
When i have similar problem i do this simple trick:
Print the size of the strings you are comparing because sometimes you have characters like \n or \r which are not visible when you print the string.
First of all, it seems like you have a typo in sysout statement below.
System.out.println("\nEntered details: " + usersName + ", " + usersPW);
System.out.println("\nSystems details: " + userName + ", " + pw); //Should be username
Secondly, you might wanna trim the strings for better string comparison.
Sometimes strings read from file or console can contain unwanted and hard-to-catch empty strings like spaces and tabs. These can be removed by calling .trim() method on strings.
Thus, try using the following code instead:
if (usersName.trim().equals(username.trim()) && usersPW.trim().equals(pw.trim())) {
}
usersName.equals(username) && usersPW.equals(pw).
I have faced these problem also, These kind of equality always tricky, Try to trim the strings that you are going to compare, as well as if you can compare these strings based on their length.
if (usersName.trim().equalsIgnoreCase(username.trim()) && usersPW.trim().equalsIgnoreCase(pw.trim()))
or
if (usersName.trim().length()==username.trim().length && usersPW.trim().length()==pw.trim().length))