Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
So I'm writing a method that is supposed to prompt the user to enter their pin number as a string, which is then converted to an int (or not depending on if it throws an exception), which I need to be assigned to the int pinNumber.
The problem I'm having is that the new object is assigned a pin number by the constructor when created, and this value isn't being changed when the below method is executed. What am I missing?
public boolean canConvertToInteger()
{
boolean result = false;
String pinAttempt;
{
pinAttempt = OUDialog.request("Enter your pin number");
try
{
int pinNumber = Integer.parseInt(pinAttempt);
return true;
}
catch (NumberFormatException anException)
{
return false;
}
}
EDIT: Changed pinAttempt to pinNumber (typo)
Have a look at this block
try
{
int pinNumber = Integer.parseInt(pinAttempt);
return true;
}
pinNumber will only have the value you expect in the scope of the try block.
I think you want to do
try
{
this.pinNumber = Integer.parseInt(pinAttempt);
return true;
}
instead.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
My requirement is to check divisibility of the input by 7, for the various test cases and I have written this code but it is throwing me NumberFormat Exception
class Solution{
int isdivisible7(String num){
// code her
long i= Long.parseLong(num);
// to convert string into long
if(i%7==0)
return 1;
else
return 0;
}
}
How can I handle the exception and return the result for any (both valid and invalid) input ?
If the input num is not number, then it will throw NumberFormatException, so you just have to catch it. Also, function names should be in camel case. And finally, it's better to make the function return boolean rather then int of values 0 and 1.
boolean isDivisibleBy7(String num){
try {
long i = Long.parseLong(num);
return i % 7 == 0;
} catch (NumberFormatException e) {
// print some error message if you want
System.out.println("You haven't passed number");
return false;
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Is there anyway to handle the exceptions in Java and prevent the program from getting terminated? For instance when the user enters an invalid number into a calculator, zero in this example for division in the denominator, I don't want the program to get terminated and show the handled exception message. I want the program to continue and ask for another input.
Could anyone clarify it with a practical example for me?
Simple: put a loop around the whole try catch block; like:
boolean loop = true;
while (loop) {
try {
fetch input
loop = false;
} catch (SomeException se) {
print some message
}
does the job in general.
Try this:
boolean exceptionOccured;
do {
try {
exceptionOccured = false;
// code to read input and perform mathematical calculation
// eg: a = 10/0;
} catch(Exception e) {
exceptionOccured = true;
System.out.pritnln("Invalid input! Please try again");
} finally {
// some code that has to be executed for sure
}
} while(exceptionOccured);
First the code inside the try block will be executed. When an execption occurs (like division by zero), execution of code jumps from try block to catch block where you can write your logic to loop the try-catch block.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
String x;
x=scanner.nextLine();
I entered 1 or 6.66.
It should give output as int or double/float. whatever is necessary.
Instead of parsing the result of scanner.nextLine() which returns a String, you should instead use the convenience methods of the Scanner class like hasNextInt() and hasNextFloat().
For example the following code should do what you expect :
if (scanner.hasNextFloat()) {
System.out.println("float");
float myValue = scanner.nextFloat();
// do something with the float myValue
}else if (scanner.hasNextInt()) {
System.out.println("int")
int myValue = scanner.nextInt();
// do something with the int myValue
} else { // fallback on string
String myValue = scanner.next();
// do something with the string myValue
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm having trouble with an assignment. What's happening is that a file is being read that reads numbers and validates if they're correct values. One of these values contains a letter and I'm trying to get my program to detect that and save the total value that should not be there. Here's the code. I'm reading the data as Strings and then converting the strings into doubles to be compared. I want to validate if the strings being read in are all numbers and then save that value for a later use. Does that make sense? for example the numbers have to be between 0 and 99999 and one value is 573S1, which wouldn't work because it contains an S. I want to save that value 573S1 to be printed as an error from the file at a later point in the code.
public static void validateData() throws IOException{
File myfile = new File("gradeInput.txt");
Scanner inputFile = new Scanner(myfile);
for (int i=0; i<33; i++){
String studentId = inputFile.next();
String toBeDouble = studentId;
Double fromString = new Double(toBeDouble);
if (fromString<0||fromString>99999){
System.out.println();
}
Any help would be greatly appreciated. Thanks a lot!
Edit: Here's what I get if I try to run the program.
Exception in thread "main" java.lang.NumberFormatException: For input string: "573S1"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1222)
at java.lang.Double.valueOf(Double.java:475)
at java.lang.Double.<init>(Double.java:567)
at Paniagua_Grading.validateData(Paniagua_Grading.java:23)
at Paniagua_Grading.main(Paniagua_Grading.java:6)
Because you are using Scanner on a file, Scanner can actually tell you this information with hasNextDouble.
while(inputFile.hasNext()) {
if(inputFile.hasNextDouble()) {
// the next token is a double
// so read it as a double
double d = inputFile.nextDouble();
} else {
// the next token is not a double
// so read it as a String
String s = inputFile.next();
}
}
This kind of convenience is the main reason to use Scanner in the first place.
You could try something like the method below, which will check if a string contains only digits -
private static boolean onlyDigits(String in) {
if (in == null) {
return false;
}
for (char c : in.toCharArray()) {
if (Character.isDigit(c)) {
continue;
}
return false;
}
return true;
}
public static void main(String[] args) {
System.out.println(onlyDigits("123"));
System.out.println(onlyDigits("123A"));
}
The output is
true
false
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am taking input as integer using Scanner class. like this:in.nextInt();
I need to prompt "wrong input" if user has entered any floating point number or character or string.
How can i accomplish this ?
nextInt() can only return an int if the InputStream contains an int as the next readable token.
If you want to validate input, you should use something like nextLine() to read a full String, and use Integer.parseInt(thatString) to check if it is an integer.
The method will throw a
NumberFormatException - if the string does not contain a parsable integer.
As I mentioned in the comments, try using the try-catch statement
int someInteger;
try {
someInteger = Scanner.nextInt();
} catch (Exception e) {
System.out.println("The value you have input is not a valid integer");
}
Put it in a try-catch body.
String input = scanner.next();
int inputInt 0;
try
{
inputInt = Integer.parseInt(input);
} catch (Exception e)
{
System.out.println("Wrong input");
System.exit(-1);
}