How to put exception for only string value? - java

I am taking input from user and it should be string only, but code is not working as I expected. Here is my code `
while(true){
try{
System.out.print("Enter test string");
str=sc.nextLine();
break;
}
catch(InputMismatchException e) {
System.out.println("Please enter String value");
continue;
}
}
System.out.println(str);
`
If I am giving integer value than it should ask again but here it is printing integer value.Also no Special character

If you tried to parse the integer directly, then you'd get a more meaningful exception to catch.
String str = "";
Scanner sc = new Scanner(System.in);
while (true) {
try {
System.out.print("Enter test string");
str = sc.nextLine();
Integer.parseInt(str);
System.out.println("Please enter String value");
} catch (NumberFormatException e) {
// You *didn't* get a number; you actually have a String now.
// You can terminate the loop here.
break;
}
}
System.out.println(str);

check if string not number like this:
while(true){
try{
System.out.print("Enter test string");
str=sc.nextLine();
if(isNumeric(str)) {
continue;
}
break;
}
catch(InputMismatchException e) {
System.out.println("Please enter String value");
continue;
}
}
System.out.println(str);
}
public static boolean isNumeric(String str)
{
for (char c : str.toCharArray())
{
if (!Character.isDigit(c)) return false;
}
return true;
}

If you are only trying to check if the string is NOT a number, you can try
String str = sc.nextLine();
if (StringUtils.isNumeric(str))
System.out.println(str);
but this method will not work if your number has a decimal or something.
check How to check if a String is numeric in Java
for a similar answer

str=sc.nextLine();
takes everything as a string hence there is no exception. Try using statement like this
int num;
&
num=sc.nextInt();
and you will find that the exception will is caught so there is no problem with the code.
Suppose that user will enter "This is 1 String" even though it contains integer but still it is a String. Same applies every time even when user enter "43728" it is still considered a String
here is how you can accomplish your goal
while(true){
System.out.print("Enter test string");
str=sc.nextLine();
Pattern pattern = Pattern.compile("\\d");
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
//System.out.println(matcher.group(0));
continue;
}
break;
}

Related

How to use scanner hasNext() to loop through a line of keyboard text and validate the user input of interger and string

I am having a problem trying to understand how I can loop through a keyboard input line of text the user will give ex:
Anika 14 Dan 16
I want to read each token and assign to String name, Int, age, String name, int age. in that order.
This is easy however, if the user enters
Anika Anika Anika Anika 13 13 13 Dan 16
Then I want the program to:
Anika,
Integer needed got String,
Integer needed got String,
Integer needed got String,
13,
String needed got Integer,
String needed got Integer,
Dan,
16
So first one will always be a string which is a word EDIT: "word", second an int and thrid string which is a "word" and fourth int.
However, I can not simulate this.
Scanner scan = new Scanner(System.in);
String name = null;
int age = 0;
String name2= null;
int age2= 0;
if(scan.hasNext() == true)
name = scan.next();
age = scan.nextInt();
name2= scan.next();
age2= scan.nextInt();
I know if I do the top I get the right order, but it is the extra inputs that I would like to ignore but write a statement expression why it's wrong and then continue to search for the next int, or third string and so on.
boolean isstring = false;
boolean isnumber = false;
do {
if (scan.hasNext())
{
name = scan.next();
isstring = true;
}
else {
System.out.println("Need String got Integer");
isstring = false;
scan.next();
}
} while (!isstring);
do {
if (scan.hasNextInt())
{
age = scan.nextInt();
isnumber=true;
}
else {
System.out.println("Need Integer got String");
isnumber=false;
scan.nextInt();
}
} while (!isnumber);
do {
if (scan.hasNext())
{
name2 = scan.next();
isstring = true;
}
else {
System.out.println("Need String got Integer");
isstring = false;
scan.next();
}
} while (!isstring);
do {
if (scan.hasNextInt())
{
age2 = scan.nextInt();
isnumber = true;
}
else {
System.out.println("Need Integer got String");
isnumber=false;
scan.nextInt();
}
} while (!isnumber);
}
I tried to use do while with ifs and It didnt work. My logic is wrong somewhere, and I think it might be the has.next() method.
Any help will be appreciated!!
If the input is a word while waiting for an Integer, it will throw InputMismatchException. nextInt() first read the value as a String an then parse it as a Integer, so if you ignore the value using nextInt, if the value is a word, it will trow the aforementioned Exception.
Using the same logic of your program
The changes should be:
Ignore the input with scan.next()
Check if a String can be or not an Integer (using scan.hasNextInt()), not if is a String, because any Integer can be expressed as a String.
boolean isstring = false;
boolean isnumber = false;
do {
if (!scan.hasNextInt()) {
isstring = true;
name = scan.next();
} else {
isstring = false;
System.out.println("Need String got Integer");
scan.next();
}
} while (!isstring);
do {
if (scan.hasNextInt()) {
isnumber = true;
age = scan.nextInt();
} else {
isnumber = false;
System.out.println("Need Integer got String");
scan.next();
}
} while (!isnumber);
do {
if (!scan.hasNextInt()) {
isstring = true;
name2 = scan.next();
} else {
isstring = false;
System.out.println("Need String got Integer");
scan.next();
}
} while (!isstring);
do {
if (scan.hasNextInt()) {
isnumber = true;
age2 = scan.nextInt();
} else {
isnumber = false;
System.out.println("Need Integer got String");
scan.next();
}
} while (!isnumber);
Using try/catch and one loop
A naive solution using try/catch can be the following
public static void main (String[]args)
{
String name = null;
String name2 = null;
Integer age = null;
Integer age2 = null;
Scanner scan = new Scanner(System.in);
while (scan.hasNext())
{
try
{
if (name == null)
{
System.out.println("Please provide name: ");
name = getNameOrFail(scan);
System.out.println("Name set: " + name);
}
if (age == null)
{
System.out.println("Please provide age: ");
age = getAgeOrFail(scan);
System.out.println("Age set: " + age);
}
if (name2 == null)
{
System.out.println("Please provide name2: ");
name2 = getNameOrFail(scan);
System.out.println("Name2 set: " + name2);
}
if (age2 == null)
{
System.out.println ("Please provide age2: ");
age2 = getAgeOrFail (scan);
System.out.println ("Age2 set: " + age2);
}
}
catch (Exception e)
{
System.out.println(e.getMessage ()); // Print the message put int Exception(message) constructor
scan.nextLine(); // Flush the Scanner cache
}
}
}
public static String getNameOrFail(Scanner scan) throws Exception
{
if (scan.hasNextInt())
throw new Exception("Need String got Integer");
return scan.next();
}
public static Integer getAgeOrFail(Scanner scan) throws Exception
{
if (!scan.hasNextInt())
throw new Exception("Need Integer got String");
return scan.nextInt();
}
Pay attention to the scan.newLine() in the catch clause, this is needed because the Scanner use a cache with the last input, so if is not re-read you enter in a infinite loop condition.
Good luck!

Sanitizing user input in Java, correcting mistakes [duplicate]

I'm new to Java and I wanted to keep on asking for user input until the user enters an integer, so that there's no InputMismatchException. I've tried this code, but I still get the exception when I enter a non-integer value.
int getInt(String prompt){
System.out.print(prompt);
Scanner sc = new Scanner(System.in);
while(!sc.hasNextInt()){
System.out.println("Enter a whole number.");
sc.nextInt();
}
return sc.nextInt();
}
Thanks for your time!
Take the input using next instead of nextInt. Put a try catch to parse the input using parseInt method. If parsing is successful break the while loop, otherwise continue.
Try this:
System.out.print("input");
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter a whole number.");
String input = sc.next();
int intInputValue = 0;
try {
intInputValue = Integer.parseInt(input);
System.out.println("Correct input, exit");
break;
} catch (NumberFormatException ne) {
System.out.println("Input is not a number, continue");
}
}
Shorter solution. Just take input in sc.next()
public int getInt(String prompt) {
Scanner sc = new Scanner(System.in);
System.out.print(prompt);
while (!sc.hasNextInt()) {
System.out.println("Enter a whole number");
sc.next();
}
return sc.nextInt();
}
Working on Juned's code, I was able to make it shorter.
int getInt(String prompt) {
System.out.print(prompt);
while(true){
try {
return Integer.parseInt(new Scanner(System.in).next());
} catch(NumberFormatException ne) {
System.out.print("That's not a whole number.\n"+prompt);
}
}
}
Keep gently scanning while you still have input, and check if it's indeed integer, as you need:
String s = "This is not yet number 10";
// create a new scanner
// with the specified String Object
Scanner scanner = new Scanner(s);
while (scanner.hasNext()) {
// if the next is a Int,
// print found and the Int
if (scanner.hasNextInt()) {
System.out.println("Found Int value :"
+ scanner.nextInt());
}
// if no Int is found,
// print "Not Found:" and the token
else {
System.out.println("Not found Int value :"
+ scanner.next());
}
}
scanner.close();
As an alternative, if it is just a single digit integer [0-9], then you can check its ASCII code. It should be between 48-57 to be an integer.
Building up on Juned's code, you can replace try block with an if condition:
System.out.print("input");
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter a whole number.");
String input = sc.next();
int intInputValue = 0;
if(input.charAt(0) >= 48 && input.charAt(0) <= 57){
System.out.println("Correct input, exit");
break;
}
System.out.println("Input is not a number, continue");
}

Check if String contains any letters from array - JAVA

String [] V = {"a","e","i","o","u"};
Scanner input = new Scanner(System.in);
String A;
System.out.println("Enter any letters");
A=input.next();
if(A.contains(V)) {
System.out.println("success");
}
bottom line. if any of the letters in "V" string are in "A" i want it to continue to "success"
Try to use a foreach loop like this:
for (String string : V) {
if(A.contains(string)) {
System.out.println("success");
}
}
Because the method contains(CharSequence) in the type String is not applicable for the arguments (String[]).
It Works Making some changes to your code
String [] V = {"a","e","i","o","u"};
boolean flag = false;
Scanner input = new Scanner(System.in);
String A;
System.out.println("Enter any letters");
A=input.next();
for(String temp:V)
{
if (A.contains(temp)) {
flag = true;
break;
}
}
if(flag)
System.out.println("Success");
else
System.out.println("Not Success");

Display an error when user enters a number instead of a string

I've tried to find something on this but have not seen anything related in the past hour of searching. I am looking to throw an error when the user tries to enter a number instead of a String.
I've found more than enough resources on how to throw and error when the user enters a string instead of a int, but nothing about the other way.
I'll just make up some code real quick
import java.util.Scanner;
public class ayylmao {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter your first name");
String AyyLmao = scan.nextLine();
System.out.println("Your first name is " + AyyLmao);
/*
Want it to say something like "Error: First character must be from the alphabet!" if the user tries to enter a number.
*/
}
}
If it's only the first character you're interested in, you could use a test like this:
if (AyyLmao.charAt(0) >= '0' && AyyLmao.charAt(0) <= '9'){
/* complain here */
}
A test on the whole string, as you apparently have found out already, would be:
try{
Integer.parseInt(AyyLmao);
/* complain here */
} catch(NumberFormatException ex){
/* this would be OK in your case */
}
Try this:
public static boolean isIntegerParseInt(String str) {
try {
Integer.parseInt(str);
return true;
} catch (NumberFormatException nfe) {}
return false;
}
Use the regular expression "^\\d" to find out if there are any digits at the start of your string.
For example, in order to check if the start of a name is a digit:
String regex = "^\\d";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(yourInput);
if(m.find()) {
// Your input starts with a digit
}
Here is a good place to get started on regular expressions:
http://www.vogella.com/tutorials/JavaRegularExpressions/article.html
private static String acceptName() {
// TODO Auto-generated method stub
Boolean flag = Boolean.TRUE;
String name = "";
while (flag) {
Scanner scan = new Scanner(System.in);
System.out.println("enter name : ");
name = scan.nextLine();
try {
Integer no = Integer.parseInt(name);
System.out.println("you have entered number....");
} catch (NumberFormatException e) {
flag = Boolean.FALSE;
}
}
return name;
}

Checking input type...how?

I have the following method:
public void addStudent(){
String fName, lName;
double mGrade, fGrade;
System.out.print("\nEnter first name: ");
Scanner in = new Scanner(System.in);
fName = in.nextLine();
System.out.print("\nEnter last name: ");
lName = in.nextLine();
System.out.print("\nEnter midterm grade: ");
mGrade = in.nextDouble();
System.out.print("\nEnter final grade: ");
fGrade = in.nextDouble();
Student toAdd = new Student(fName, lName, mGrade, fGrade);
students.add(toAdd);
System.out.println("\nStudent record added.\n");
System.out.println(students.size());
}
How can I check if the user typed in something other than an integer for midterm grade and final grade? And if they entered a non-integer, I want the method to just request the user type in that value again. I'm guessing I'll have to use a do-while loop. But I don't don't know how to check the type...
Thanks!
You can use Scanner.next() and try to parse it to the type you want (ex. to integer by using Integer.parseInt(x) and if it fails (throws and exception) try to do it again.
Yes, a do-while will work best.
int midterm;
System.out.printLn("Enter midterm grade");
do
{
try {
string s = in.nextLine();
midterm = Integer.parseInt(s);
break;
}
catch (Exception e)
{
System.out.printLn("Couldn't parse input, please try again");
}
}
while (true);
You may use the method: nextInt() from Scanner
Alternatively you can check if a string is an integer like this:
if( someString.matches("\\d+") ) {
// it is
} else {
// it isn't
}
Run the input method in a loop, if user enters something other than valid integer or double, repeat asking for the input.
you can try this
import java.io.*;
import java.util.Scanner;
public class Test {
public static void main(String args[]) throws Exception {
String input;
int ch1;
float ch2;
String ch3;
Scanner one = new Scanner(System.in);
input = one.nextLine();
try {
ch1 = Integer.parseInt(input);
System.out.println("integer");
return;
} catch (NumberFormatException e) {
}
try {
ch2 = Float.parseFloat(input);
System.out.println("float");
return;
} catch (NumberFormatException e) {
}
try {
ch3 = String.valueOf(input);
System.out.println("String");
} catch (NumberFormatException e) {
}
}
}

Categories

Resources