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);
}
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
The question is duplicate but I can't find a proper solution so please help me out with this,
I have to convert the credit card number(from edittext) to int.
Credit card number like : "3333 3333 3333 3333"
I removed white space using String removeWhiteSpace = cardNumEt.getText().toString().replace(" ", "");
Than converted to int like :
try
{
int nIntFromET = Integer.parseInt(removeWhiteSpace);
}
catch (NumberFormatException e)
{
Log.e("exptn",e.toString());
}
but unfortunately it's giving me exception :
java.lang.NumberFormatException: For input string: "3333333333333333"
The int type in Java can be used to represent any whole number from -2147483648 to 2147483647.
Your value is above the maximum positive integer.
But you can use instead long and BigInteger
class Scratch {
public static void main(String[] args) {
try
{
int nIntFromET = Integer.parseInt("2147483647");
}
catch (NumberFormatException e)
{
System.out.println(e);
}
}
}
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 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 8 years ago.
Improve this question
try {
System.out.println("how many times");
rollnumber = scanner.nextInt();
nigh=2;
}catch (Exception e){
System.out.print("invalid. re-enter");
}
}while (nigh==1);
It keeps printing out infinity "invalid re-enterhow many times"
You get into an infinite loop because scanner.nextInt(); does not consume characters from the input on error. Change the catch clause as follows to make it work:
try {
... // Your code
} catch (Exception e){
System.out.print("invalid. re-enter");
scanner.nextLine();
}
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'm having a trouble figuring out how to solve this issue when it just stops when I call this method when I input letters and other types. What is the problem with my code? Can anyone help? Thanks in advance!
Here is my code:
public int selectOption(int maxRange, String sourceType) throws IOException
{
do
{
try
{
userInput = input.nextInt();
}//end try
catch(Exception e)
{
validInput=false;
input.next();
}//end catch
if (userInput<1 || userInput>maxRange)
{
MovieHouse.clearScreen();
System.out.println("Select from the options only!");
loadHeader();
if(sourceType.equals("main"))
MovieHouse.homeMenu();
else if(sourceType.equals("movie menu"))
loadMovieMenu();
}//end if
}while(userInput<1 || userInput>maxRange || validInput==false);
return userInput;
}//end selectOption
"input letters" - Does it mean normally the program take digits and you are providing char as input.
Not clear what is your issue.
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
In an interview I was asked a question like:
Take an input from console like: "welcome to world" and count a particular character entered by the user at which index and how many times(i.e. occurance of the character) without using any built-in methods like charAt(int ind) etc.
Giving you a potted answer won't help you at all. Here's how you can achieve what you want. Try to code it yourself.
Convert your String to a Character Array.
Have a Map which would store the char element as the key and its count as the value.
Iterate over the char array and for each element, check if its already existing in the map.
a. If it exists, increment the value for that element by 1 and put it back in the map.
b. If it doesn't, insert that char along with 1 as its count value in the map.
Continue till there are more elements in the char array.
The map now has all the char along with their respective counts.
import java.io.Console;
class dev
{
public static void main(String arg[])
{
Console c=System.console();
String str=c.readLine();
System.out.println(str);
int times=0;
//find c character
char find='c';
char strChar[]=str.toCharArray();
System.out.print("positions of char c in the string :");
try
{
for (int i=0; ;i++ )
{
if(strChar[i]==find)
{
System.out.print((i-1)+", ");times++;
}
}
}
catch (Exception e)
{
System.out.println("\n"+"The no. of times c occur : "+times);
}
}
}