Im trying to make a simple calculation program but i keep getting this error whenever I try to run the code. How can i avoid this?
TextField inputOne = new TextField("Input first data");
// Making output 1
int inputNumber = Integer.parseInt(inputOne.getText());
Always get error message java.lang.reflect.InvocationTargetException
at line 25 where the parse int is placed
getText() function returns the input value of the user, or the "Input first data" String? if it returns the input value of the user then it is probably a NumberFormatException that you should handle, else it is because the String mentioned is the mistake.
Related
So I wanna create this program that stores 4 values. the first one being string and the remaining 3 being integers. However, when i enter 4 values and press enter, i get an error java.util.InputMismatchException but when I enter 5 values, i get the result for my for values. for example lets say i input the following values:
Japan,1,2,3
I will get the java.util.InputMismatchException error. And if I enter the following values:-
Japan,1,2,3,4
I get the output as I want:-
Japan,1,2,3
Why is this happening? Here is my code
public class satisfaction {
public static void main(String args[])
{
Scanner src= new Scanner(System.in);
src.useDelimiter("\\,|\\n");
String name=src.next();
int a=src.nextInt();
int b=src.nextInt();
int c=src.nextInt();
System.out.println(name+","+a+","+b+","+c);
}
}
I've tested this a bit myself, and I think the \n in the pattern is not matching the line ending used by your console.
For me, I had to use \r\n instead, but you could also use System.lineSeparator() e.g. like this:
src.useDelimiter(",|" + System.lineSeparator());
The way it's written, it needs another comma at the end of the input. I would recommend checking the string to make sure it ends in a comma, and if not, append one.
I believe that if you enter Japan,1,2,3, it will give you the output you want.
This question already has answers here:
How to keep my user input on the same line after an output?
(4 answers)
Closed 3 years ago.
I want to print a line like this:
Result: [the result are input here and after click on Enter to continue]
How can I do that?
EDIT:
This is what I want:
Scanner user1 = new Scanner(System.in);
int x = user1.nextInt();
System.out.println("Result: "+x);
But the last line won't print unless I type my input and press Enter.
Using java, you simply could use System.out.print(); to display it in console and after adding the capture info:
System.out.print("Result: ");
int x = user1.nextInt();
This is a very old thread but since there doesn't seem to be an accepted answer, I am answering. Hope it would help someone else...
Here is what you are looking for
Scanner input = new Scanner (System.in);
System.out.print("Enter a number : ");
int num = input.nextInt();
System.out.println("Hello you entered "+num);
Note that when you use println the cursor moves to next line.
If you use just print the next statement continues on the same line.
Hope this one will work. Please try
Input str =scanner. readLine("Result:" ) ;
Int inp =integer.parseInt(star) ;
The last line will not print unless you type an input and press enter as the code is run line by line. First you have to enter the value. Since it runs on console for the next step to be pressed you have to press enter.
So whatever you said will naturally happen and cannot be avoided.
Based on the code snippet you sent there is nothing wrong with the code and the logic in it and these are basic java steps.
I'm trying to validate my program by entering a value through a JTextField on a JDialog and if it's less than a value..., else do ... I keep running into a problem on the line:
int intDiagInput = Integer.parseInt(dialogInput)
JOptionPane.showInputDialog(dialogPaneInput, "Age verification required, please enter year of birth: yyyy");
dialogInput = dialogPaneInput.getText(); //get info from JTextField and put in string
int intDiagInput = Integer.parseInt(dialogInput); //convert string to int
Any help would be greatly appreciated.
Your code is wrong in two ways:
The first paramenter you pass to showInputDialog is used as the parent, just for layout purposes, it has nothing to do with the actual content of the input dialog. Therefore your second error is getting the text from the displayed dialog.
To get the text the users enters you need to write something like:
String dialogInput = JOptionPane.showInputDialog(dialogPaneInput, "Age verification required, please enter year of birth: yyyy");
int intDiagInput = Integer.parseInt(dialogInput ); //convert string to int
What you are doing is getting the text of some magical object dialogPaneInput, which probably is just an empty string.
Additionally you should check that the user inputs a valid number, not in terms of a number that you would accept but in terms of it actually beeing a number, otherwise you will run into the already existent NumberFormatException - or wrap the parsing in a try...catch-block.
try {
int intDiagInput = Integer.parseInt(dialogInput );
} catch (NumberFormatException nfex) {
System.err.println("error while trying to convert input to int.");
}
The exception you posted on the comment section (java.lang.NumberFormatException: For input string: "") means that you're trying to convert an empty String to int.
Change your code to verify if dialogInput is not empty before converting it to int.
[NOTE] Add to the answer below for other good tips for reading the stack trace
I am getting an error in a program that I am making and I don't know how to fix it.
The user has to choose options from messageboxes, and I have to use the users input to calculate the tuition they will have and their discount.
If I run it!
run: Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:468)
at java.lang.Integer.parseInt(Integer.java:497)
at cabrera.Main.main(Main.java:26)
Java Result: 1
BUILD SUCCESSFUL (total time: 6 seconds)
Code
package cabrera;
/**
*
* #author Owner
*/
import javax.swing.JOptionPane;
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String tuition1 = "", scholar1 = "";
int tuition = 0, scholar = 0;
double discount = 0.0;
JOptionPane.showInputDialog("Input Your Tuition" + tuition1);
JOptionPane.showInputDialog("Choose A Scholar Discount:" + "\n• 1 = 80% " + "\n• 2 = 50%" + "\n• 3 = 25%" + "\n• 4 = No Discount !" + scholar1);
tuition = Integer.parseInt(tuition1);
scholar = Integer.parseInt(scholar1);
JOptionPane.showMessageDialog(null, "Your Total Tuition is: " + tuition);
// If-elseif-else statements based on scholar variable
}
}
How do I fix this error message?
More Info
I recently came across a question that was badly executed. Bad title, bad code, bad question (actually not question, but it could be assumed after some thought). It was from a new SO user.
I wanted to help out and looked at the code for a while. So I edited the post; fixed the code layout, simplified the code, ask the question the OP wanted to ask, etc.... That question is now above; however, the question was put on hold, and I read that questions can take a long time to get off of On Hold. You need something like 5 votes to reopen after it is put on hold. Something I don't see that will happen given that it has been a while since the question was first asked.
I had the answer complete and don't want to waste a good answer
OK, lets look at how to find the issue first!
(3) run: Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:468)
(2) at java.lang.Integer.parseInt(Integer.java:497)
(1) at cabrera.Main.main(Main.java:26)
Java Result: 1
BUILD SUCCESSFUL (total time: 6 seconds)
Look at...
(1), here you can see in Main.java you have an issue on line 26
(2), here you can see more information on the issue. In fact you know you have an issue with Integer.parseInt.
You Don't have to worry about looking at this code, because you don't have a class called Integer with method parseInt in the package java.lang
You just know there is an issue here, and it deals with Integer.parseInt which you do call in your Main.java code!
So we located a possible area to check for the error!
tuition = Integer.parseInt(tuition1);
scholar = Integer.parseInt(scholar1);
(3), here we can see that a NumberFormatException was throw because you gave it (the Integer.parseInt that is) an input of "" (an empty string)
So How do you fix it?
First, you have to look at the input of Integer.parseInt
You can see you pass in tuition1 and scholar1
Look to see where those 2 variable are changed / created.
You can see the last thing you did was create those two variables and assigned them the empty string ("")
There is the problem!!
So you need to assign them a value from the user. That will be done via the showInputDialog(...).
the showInputDialog(...) returns a value that you can use! See here!
All you have to do is...
tuition1 = JOptionPane.showInputDialog("Input Your Tuition");
scholar1 = JOptionPane.showInputDialog("Choose A Scholar Discount: 1... 2... 3... 4...")
Take note that tuition1 and scholar1 should NOT be placed inside of the dialog box when you want to assign them values from the user. You need to have the user input some text into the dialog box, and that value will be returned when you press the OK button. So you have to assign that return value to tuition1 and scholar1
You are getting this exception because user is free to enter an input which is not a number. Integer.parseInt(String s) will throw a NumberFormatException if the argument passed to this method is not a valid number. You can restrict the user to input only numbers by the use of regular expressions. The code is below:
String tuition1="";
int tuition = 0;
boolean numFound =false;
try{
while(!numFound){
tuition1 = JOptionPane.showInputDialog("Input Your Tuition:");
Pattern p = Pattern.compile("[A-Z,a-z,&%$##!()*^]");
Matcher m = p.matcher(tuition1);
if (m.find()) {
JOptionPane.showMessageDialog(null, "Please enter only numbers");
}
else{
tuition = Integer.parseInt(tuition1);
numFound = true;
}
}
}
catch (Exception e) {
e.printStackTrace();
}
This will show a message to user "Please enter only numbers", if he tries to enter something that cannot be converted to integer.
I am making a decryption program and I'm not quite sure how to use the variable "cip" out side of my try catch block. I tried moving the 3 lines of where is asks user to input pattern but i ran into other problems.
my code is:
import java.util.*;
public class unscrambler //This class will encrpyt the program
{
public static void main (String [] args){
int cip= 0;
String user ="";
System.out.println("Please enter the code to unscramble");
Scanner inputScanner = new Scanner(System.in); //imports scanner reader
String userinput = inputScanner.next();
char[] charArray = userinput.toCharArray(); //sends userinput to charArray
int j=charArray.length;
Character [] array = new Character[j];
for(int w=0; w<j; w++){
array[w] = charArray[w];
}
int a=1;
System.out.println("Please enter the number cipher pattern (an integer)");
do{
try{
user = inputScanner.next();
cip = Integer.parseInt(user);
a=2;
System.out.println("your code is ");
for(int w =0; w<j;){
System.out.println(charArray[j]);
w+=cip;
}
if(cip<=0){
System.out.println("please enter number greater than zero");
a=1;
}
}catch(NumberFormatException f){
System.out.println("please enter a proper number");
}
}while(a==1);
}
}
You're only making the declarations in that block.
String user = inputScanner.next();
int cip = Integer.parseInt(user);
Add these to the start of the file, just after the main() line:
int cip = 0;
String user = "";
The errors after just moving (without the = stuff) indicate that you're using cip after the try block, so we need to initialise it with empty data in case the try fails.
Now just change the lines that you've currently got in the try block to:
// Remove the 'String' part.
user = inputScanner.next();
// Remove the 'int' part.
cip = Integer.parseInt(user);
And then you can move on to the next unrelated bug.
The solution is to either move the variable declaration outside of the loop, or move the place you want to use it inside the loop.
Java doesn't allow you to use a local variable outside of the scope in which it was declared. Period.
I tried moving the 3 lines of where is asks user to input pattern but i ran into other problems.
Well ... you need to solve those other problems!
Programming is like this. You need to work within the constraints of the programming language that you are using.
I can see what is causing your latest error, but I'm not going to tell you what it is. Instead, I'm going to tell you how to find it for yourself.
The "line upon line of output" is a Java Stacktrace. It contains A LOT of useful information, and you need to learn how to interpret it.
java.lang.ArrayIndexOutOfBoundsException: 5
at unscrambler.main(unscrambler.java:35)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
Stacktraces typically report an exception that has been thrown somewhere in your running program.
Step 0: Find the stacktrace.
The first line gives the name of the exception, and the message. In this case, the name of the exception is ArrayIndexOutOfBounds and the message is (just) "5".
Step 1: If you don't recognize the name of the exception, look it up in the javadocs.
Here it is: link. Read it now.
Step 2: Try to understand the message. In this case, you just need to know that the message is the value of the index that was out of range. But you should be able to guess that ... based on the javadoc for the exception. (Usually the messages are a bit more informative, but this one is being thrown from compiled code, and for technical reasons a more informative error would be difficult to produce.)
The second line of the stacktrace tells you where the exception was thrown. In this case, line 35 of "unscrambler.java" ... in the main method.
Step 3: Open the source file in an editor or your IDE, and see what the code at that line says.
In this case it is (I think) this line:
System.out.println(charArray[j]);
Step 4: Now you have to start thinking. (Thinking is a very important part debugging!) How can that line have possibly thrown that exception? What could have caused that?
In this case, the first think to observe is that there is only one place on that line where you are doing array indexing, and it is the expression charArray[j]. So that means that ... (you fill in the details). But were did ... (you fill in the details) come from? Take a look at what happened before this statement. See it yet? (If no, then look again. It should be really obvious if you look carefully!)
The rest is for you to sort out ... :-)