how can i get the following code to repeat input() until a numeric is entered and at the same time tell the user what type of of variable was entered,be it string,double or integer and if conditions are met prints out a success message?
package returnin;
import java.util.*;
public class trycatch {
public static void main(String[]args){
String chck=input();
String passed =check(chck);
System.out.println("If you see this message it means that you passed the test");
}
static String input(){
Scanner sc= new Scanner(System.in);
System.out.println("Enter a value");
String var=sc.nextLine();
return var;
}
static String check(String a){
double d = Double.valueOf(a);
if (d==(int)d){
System.out.println( "integer "+(int) d);
}
else {
System.out.println(" double "+d);
}
return a;
}
}
Here's a commented example:
package returnin;
import java.util.*;
public class trycatch {
public static void main(String[] args) {
// Don't recreate Scanner inside input method.
Scanner sc = new Scanner(System.in);
// Read once
String chck = input(sc);
// Loop until check is okay
while (!check(chck)) {
// read next
chck = input(sc);
}
System.out.println("If you see this message it means that you passed the test");
}
static String input(Scanner sc) {
System.out.println("Enter a value");
return sc.nextLine();
}
static boolean check(String a) {
try {
// Try parsing as an Integer
Integer.parseInt(a);
System.out.println("You entered an Integer");
return true;
} catch (NumberFormatException nfe) {
// Not an Integer
}
try {
// Try parsing as a long
Long.parseLong(a);
System.out.println("You entered a Long");
return true;
} catch (NumberFormatException nfe) {
// Not an Integer
}
try {
// Try parsing as a double
Double.parseDouble(a);
System.out.println("You entered a Double");
return true;
} catch (NumberFormatException nfe) {
// Not a Double
}
System.out.println("You entered a String.");
return false;
}
}
Related
I'm trying to make a program where a user needs to input a random integer. If the user inputs a String I want an error message to pop out: "This is not a number" and after that restart the program until the user inputs a number. I got this so far and I'm stuck. I just get an error message if I input a string and program crashes.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number = 0;
do {
System.out.println("Input a number!");
number = scanner.nextInt();
if (!scanner.hasNextInt()) {
System.err.println("This is not a number");
}
} while (!scanner.hasNextInt());
System.out.println("You entered: " + number);
}
You're getting an InputMisMatchException because if you input a string into a scanner.nextInt(), it will immediately give an error and stop the program before it does anything else, so it won't reach your if statement. One way to get around this issue is to instead receive user input as a string, try to parse it for an int, and end the loop if it doesn't throw an exception. This is my implementation:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String input = "";
int number = 0;
boolean end = true;
do {
System.out.println("Input a number!");
input = scanner.nextLine();
try {
number = Integer.parseInt(input);
end = true;
} catch(Exception e) {
System.err.println("This is not a number");
end = false;
}
} while (!end);
System.out.println("You entered: " + number);
}
See if the below code can help achieve what you want to do.
public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String number;
do {
System.out.println("Input a number!");
number = scanner.next();
} while (!isNumeric(number));
System.out.println("You entered: " + number);
}
public static boolean isNumeric(final String str) {
// null or empty
if (str == null || str.length() == 0) {
return false;
}
return str.chars().allMatch(Character::isDigit);
}
}
Scanner sc = new Scanner(System.in);
System.out.println("Enter whatever you want");
String st = sc.nextLine();
try {
String d = String.valueOf(st);
if (d == (String) d) {
System.out.println((String) d);
} else {
System.out.println(d);
}
} catch(Exception e) {
System.out.println("integer");
}
When I try to execute this, it keeps printing "if" part even for integer and double.
Any input can be evaluated as a string, even if it is "2.9". Instead, you could use Scanner's hasXYZ methods:
if (sc.hasNextInt()) {
System.out.println("Integer");
} else if (sc.hasNextDouble()) {
System.out.println("Double");
} else {
System.out.println("String");
}
In order to use your code:
Try to parse to integer first. If this is successful it means you have an int. If this doesn't work try parsing to a double, again if this works it means you have a double otherwise you have a string.
Use Integer.valueOf and Double.valueOf:
System.out.println("Enter whatever you want");
String st = sc.nextLine();
try {
Integer d = Integer.valueOf(st);
System.out.println("Integer: " + d);
} catch (NumberFormatException e) {
try {
Double d = Double.valueOf(st);
System.out.println("Double: " + d);
}catch (NumberFormatException nf) {
System.out.println("String: " + st);
}
}
But I wouldn't build it this way. A better option is to use sc.hasNextInt and sc.hasNextDouble
You can use this program to output the type:
import java.util.Scanner;
public class MyTest {
public static void main(String args[]) throws Exception {
Scanner sc = new Scanner(System.in);
System.out.println("Enter whatever you want");
String st = sc.nextLine();
try {
Integer.parseInt(st);
System.out.println("Integer");
} catch (NumberFormatException nfe) {
try {
Double.parseDouble(st);
System.out.println("Double");
} catch (NumberFormatException nfe2) {
System.out.println("String");
}
}
sc.close();
}
}
try this:
String d= String.valueOf(st);
try{
//If double or integer comes here
double val = Double.parseDouble(d);
}catch(Exception e){
//If String comes here
}
I have to keep inputting x and y coordinates, until the user inputs "stop". However, I don't understand how to parse the input from String to int, as whenever I do, I get back errors.
public class Demo2 {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
while (true) {
System.out.println("Enter x:");
String x = kb.nextLine();
if (x.equals("stop")) {
System.out.println("Stop");
break;
}
System.out.println("Enter y:");
String y = kb.nextLine();
if (y.equals("stop")) {
System.out.println("Stop"); }
break;
}
}
}
}
To Parse integer from String you can use this code snippet.
try{
int xx = Integer.parseInt(x);
int yy = Integer.parseInt(y);
//Do whatever want
}catch(NumberFormatException e){
System.out.println("Error please input integer.");
}
Nice way to do this in my opinion is to always read the input as a string and then test if it can be converted to an integer.
import java.util.Scanner;
public class Demo2 {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
while (true) {
String input;
int x = 0;
int y = 0;
System.out.println("Enter x:");
input = kb.nextLine();
if (input.equalsIgnoreCase("STOP")) {
System.out.println("Stop");
break;
}
try {
x = Integer.parseInt(input);
System.out.println(x);
} catch (NumberFormatException e) {
System.out.println("No valid number");
}
}
}
}
With
String variablename = Integer.toString(x);
I am wondering how I can check if a user's input is a certain primitive type (I mean integer, String, etc... I think it's called primitive type?). I want a user to input something, then I check if it's a String or not, and do a certain action accordingly. (JAVA)
I have seen some codes like this:
if (input == (String)input) { (RANDOM STUFF HERE) }
or something like
if input.equals((String) input)
And they don't work. I want to know how I can Check for only a String? (EDITED OUT)
I was wondering if there was a function that can do that? Thanks for the answers
EDIT: With the help of everyone I have created my fixed code that does what I want it to:
package files;
import java.util.*;
public class CheckforSomething {
static Scanner inputofUser = new Scanner(System.in);
static Object userInput;
static Object classofInput;
public static void main(String[] args){
try{
System.out.print("Enter an integer, only an integer: ");
userInput = inputofUser.nextInt();
classofInput = userInput.getClass();
System.out.println(classofInput);
} catch(InputMismatchException e) {
System.out.println("Not an integer, crashing down");
}
}
}
No need for answers anymore, thanks!
Use instanceof to check type and typecast according to your type:
public class A {
public static void main(String[]s){
show(5);
show("hello");
}
public static void show(Object obj){
if(obj instanceof Integer){
System.out.println((Integer)obj);
}else if(obj instanceof String){
System.out.println((String)obj);
}
}
}
You may try this with Regex:
String input = "34";
if(input.matches("^\\d+(\\.\\d+)?")) {
//okay
} else {
// not okay !
}
Here,
^\\d+ says that input starts with a digit 0-9,
()? may/or may not occur
\\. allows one period in input
Scanner input = new Scanner (System.in);
if (input.hasNextInt()) System.out.println("This input is of type Integer.");
else if (input.hasNextFloat()) System.out.println("This input is of type Float.");
else if (input.hasNextLine()) System.out.println("This input is of type string.");
else if (input.hasNextDouble()) System.out.println("This input is of type Double.");
else if (input.hasNextBoolean()) System.out.println("This input is of type Boolean.");
else if (input.hasNextLong())
System.out.println("This input is of type Long.");
Hate to bring this up after 6 years but I found another possible solution.
Currently attending a coding bootcamp and had to solve a similar problem. We introduce booleans and change their values depending on the result of the try/catch blocks. We then check the booleans using simple if statements. You can omit the prints and input your code instead. Here's what it looks like:
import java.io.IOException;
import java.util.Scanner;
public class DataTypeFinder {
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
String input = "";
while (true) { //so we can check multiple inputs (optional)
input = scan.nextLine();
if ("END".equals(input)) { //a way to exit the loop
break;
}
boolean isInt = true; //introduce boolean to check if input is of type Integer
try { // surround with try/catch
int integer = Integer.parseInt(input); //boolean is still true if it works
} catch (NumberFormatException e) {
isInt = false; //changed to false if it doesn't
}
boolean isDouble = true; //same story
try {
double dbl = Double.parseDouble(input);
} catch (NumberFormatException e) {
isDouble = false;
}
if (isInt) {
System.out.printf("%s is integer type%n", input);
} else if (isDouble) {
System.out.printf("%s is floating point type%n", input);
} else if (input.length() == 1) { //this could be useless depending on your case
System.out.printf("%s is character type%n", input);
} else if ("true".equals(input.toLowerCase()) || "false".equals(input.toLowerCase())) {
System.out.printf("%s is boolean type%n", input);
} else {
System.out.printf("%s is string type%n", input);
}
}
}
}
class Main{
public static void main(String args[]){
String str;
Scanner sc=new Scanner(System.in);
int n,
boolean flag=false;
while(!flag){
try{
str=sc.nextLine();
n=Integer.parseInt(str);
flag=true;
}
catch(NumberFormatException e){
System.out.println("enter an no");
str=sc.nextLine();
}
}
}
}
Is this ok?
class Test
{
public static void main(String args[])
{
java.util.Scanner in = new java.util.Scanner(System.in);
String x = in.nextLine();
System.out.println("\n The type of the variable is : "+x.getClass());
}
}
Output:
subham#subham-SVE15125CNB:~/Desktop$ javac Test.java
subham#subham-SVE15125CNB:~/Desktop$ java Test
hello
The type of the variable is : java.lang.String
But Zechariax wanted an answer with out using try catch
You can achieve this using NumberForamtter and ParsePosition.
Check out this solution
import java.text.NumberFormat;
import java.text.ParsePosition;
public class TypeChecker {
public static void main(String[] args) {
String temp = "a"; // "1"
NumberFormat numberFormatter = NumberFormat.getInstance();
ParsePosition parsePosition = new ParsePosition(0);
numberFormatter.parse(temp, parsePosition);
if(temp.length() == parsePosition.getIndex()) {
System.out.println("It is a number");
} else {
System.out.println("It is a not number");
}
}
}
Try instanceof function with Integer instead of int.. each primitive also have a class
I am new in java. I have written a program in which the user chooses how many numbers he wants to add. If the user enters a string it will throw an exception and the programs tell the user to enter all details again.
My problem is i want the program to ask the user to re enter details from that number which he entered wrong.
Eg: the user chooses to add 4 numbers but he enters the third number as string, the program should ask the user to re-enter from the third number and not the entire details again.
My code is as follow:
import java.io.*;
import java.util.*;
class Add
{
public static void main(String args[]) throws Exception
{
boolean loop=true;
while(loop)
try
{
String yn;
do
{
Scanner s=new Scanner(System.in);
System.out.println("Enter how many numbers to add: ");
int num=Integer.parseInt(s.next());
int a,sum=0;
for(int i=1;i<=num;i++)
{
System.out.println("Enter number["+i+"]: ");
a=Integer.parseInt(s.next());
sum=sum+a;
}
System.out.println("The Sum is:"+sum);
System.out.println("Do you want to continue?(Y/N):");
yn=s.next();
} while(yn.equals("y")||yn.equals("Y"));
}
catch(Exception e)
{
System.out.println("Try Again\n");
}
}
}
You can resolve this, by placing the "retry" one level deeper in the code:
import java.io.*;
import java.util.*;
class Add {
public static void main(String args[]) throws Exception {
boolean loop=true;
Scanner s=new Scanner(System.in);
while(loop) {
try {
String yn;
do {
loop = true;
System.out.println("Enter how many numbers to add: ");
int num=Integer.parseInt(s.next());
int a,sum=0;
for(int i=1;i<=num;) {
try {
System.out.println("Enter number["+i+"]: ");
a=Integer.parseInt(s.next());
sum=sum+a;
i++;
}
catch(Exception e) {
System.out.println("Invalid input. Try Again.\n");
}
}
System.out.println("The Sum is:"+sum);
System.out.println("Do you want to continue?(Y/N):");
yn=s.next();
loop = yn.equals("y")||yn.equals("Y");
} while(loop);
}
catch(Exception e) {
System.out.println("Number of elements invalid. Try Again.\n");
}
}
}
}
As #Zhuinden indicates, one better uses Scanner.nextInt, since it is more generic...
Below code should help
int i =1;
while(i <=num){
System.out.println("Enter number["+i+"]: ");
try{
a=Integer.parseInt(s.next());
sum=sum+a;
i++;
}catch(NumberFormatException ex){
System.out.println("Please enter a valid interger");
}
}
Use additional method that reads single entry until it is valid number:
private static int readNumber(Scanner s) {
Integer value = null;
while (value == null) {
try {
value = Integer.parseInt(s.next());
} catch (NumberFormatException e) {
System.out.println("bad format, try again...");
}
}
return value;
}
Then you can use this method whenever you can read valid number:
System.out.println("Enter how many numbers to add: ");
int num = readNumber(s);
...
System.out.println("Enter number[" + i + "]: ");
a = readNumber(s);
....
Method getNumber(s) guarantee to return only when user give correct integer.
works according to what you want, but not ethical
import java.io.*;
import java.util.*;
class Add
{
public static void main(String args[]) throws Exception
{
boolean loop=true;int pos=0;int num=0,sum=0;
while(loop)
try
{
String yn;
do
{sum=0;num=0;
Scanner s=new Scanner(System.in);
System.out.println("Enter how many numbers to add: ");
num=Integer.parseInt(s.next());
int a;
for(int i=1;i<=num;i++)
{
System.out.println("Enter number["+i+"]: ");
a=Integer.parseInt(s.next());
sum=sum+a;pos=i;
}
System.out.println("The Sum is:"+sum);
System.out.println("Do you want to continue?(Y/N):");
yn=s.next();
} while(yn.equals("y")||yn.equals("Y"));
}
catch(Exception e)
{
Scanner s=new Scanner(System.in);
int a=0;
for(int i=pos+1;i<=num;i++)
{ System.out.println("Enter number["+i+"]: ");
a=Integer.parseInt(s.next());
sum=sum+a;}
System.out.println("The Sum is:"+sum);
}
}
}