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
}
Related
What should be the syntax to get StdInput and StdOutput in Java.
I need to take input from user, which could be in any order and any data type (int, float, string). My code takes so, but it does not allow the flexibility to accept data types in random order.
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
double y = sc.nextDouble();
sc.nextLine();
String s = sc.nextLine();
System.out.println("String: " + s);
System.out.println("Double: " + y);
System.out.println("Int: " + x);
How do I get the input in any order irrespective of the data type?
It depends on what you want with the input.
But one thing you can do, is take the input as a string and then inspect the contents of the string. For example, you can trail and error on the datatype using the parseInt() and parseDouble() methods. Something like this:
try {
// Try to parse it as an integer
Integer.parseInt(input);
}
catch (NumberFormatException exc) {
try {
// Try to parse it as a double
Double.parseDouble(input);
}
catch (NumberformatException exc) {
// Else, it's a string
}
}
However, below a more elegant way:
Scanner sc = new Scanner(System.in);
while (true) { // Some condition
if (sc.hasNextInt()) {
int i = sc.nextInt();
System.out.println("int: " + i);
}
else if (sc.hasNextDouble()) {
double d = sc.nextDouble();
System.out.println("double: " + d);
}
else {
String s = sc.next();
System.out.println("string: " + s);
}
}
Note that the decimal separator is locale-dependent.
If you want to determine the type of the data from an arbitrary type, your only option (when using a Scanner) is to use nextLine() (or next()). These methods return a String which you can parse to the datatype you want, for example:
String s = sc.nextLine();
// For an integer
int i = Integer.parseInt(s);
// For a double
double i = Double.parseDouble(s);
You can do something like,
Scanner in = new Scanner(System.in);
in.useDelimiter(" ");
while(in.hasNext()) {
String s = in.next();
try {
Double d = Double.valueOf(s);
d += 1;
System.out.print(d);
System.out.print(" ");
} catch(NumberFormatException e) {
StringBuffer sb = new StringBuffer(s);
sb.reverse();
System.out.print(sb.toString() + " ");
}
}
Scanner has methods like hasNextInt and hasNextDouble to determine what type the next token is, so you can branch based on that:
Scanner sc = new Scanner(System.in);
while (true) {
if (sc.hasNextInt()) {
int i = sc.nextInt();
System.out.println("Int: " + i);
} else if (sc.hasNextDouble()) {
double d = sc.nextDouble();
System.out.println("Double: " + d);
} else {
String s = sc.next();
if (s.equals("END")) break; // stop condition
System.out.println("String: " + s);
}
}
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;
}
}
Alright so I am an intro student in a programming class and I am trying to test a catch statement of a NFE. I don't know how to format the code properly, but here it is.
import java.util.Scanner;
public class Geo {
public static void main(String[] args) {
try {
Scanner inp = new Scanner(System.in);
System.out.print("Name?");
String name = inp.nextLine();
System.out.print("Number?");
double num = inp.nextDouble();
System.out.print("Integer?");
int num2 = inp.nextInt();
} catch(NumberFormatException e) {
System.out.println("Usage error");
}
System.out.println(name);
System.out.println(num);
System.out.println(num2);
}
}
It keeps saying the variables, name, num, and num2 are undefined. What am I doing wrong here, because I was looking back at an old lab and that is exactly how I had done it before. Any hints?
Now I fixed it so the code looks like this
public static void main(String[] args) {
try {
Scanner inp = new Scanner(System.in);
System.out.print("Name?");
String name = inp.nextLine();
System.out.print("Number?");
double num = inp.nextDouble();
System.out.print("Integer?");
int num2 = inp.nextInt();
System.out.println(name);
System.out.println(num);
System.out.println(num2);
} catch(NumberFormatException e) {
System.out.println("Usage error");
}
}
but the catch isnt running. How does that get fixed. Like I want it run the try completely, but if something is wrong it keeps running, then out of try, then catches the issue.
You must initial variables on top of try/catch.
public static void main(String[] args) {
String name = null;
double num = 0;
int num2 = 0;
try {
Scanner inp = new Scanner(System.in);
System.out.print("Name?");
name = inp.nextLine();
System.out.print("Number?");
num = inp.nextDouble();
System.out.print("Integer?");
num2 = inp.nextInt();
} catch (Exception e) {
System.out.println("Usage error");
}
System.out.println(name);
System.out.println(num);
System.out.println(num2);
}
or
public static void main(String[] args) {
try {
Scanner inp = new Scanner(System.in);
System.out.print("Name?");
String name = inp.nextLine();
System.out.print("Number?");
double num = inp.nextDouble();
System.out.print("Integer?");
int num2 = inp.nextInt();
System.out.println(name);
System.out.println(num);
System.out.println(num2);
} catch (Exception e) {
System.out.println("Usage error");
}
}
The variables you are referring to are defined in the try block and are therefore visible only in it, while you are trying to read them outside of the try block.
You can either do the printing in the try block, or define the variables in main function.
So I've recently learned exception handling for Java and I'm still trying to get used to it and all but I feel like I'm missing something. I was doing an assignment for my class and the compiler doesn't like my code.
I'm supposed to be making a Calculator that takes in an operator and then a number, and if the operator (+, -, *, /) given is not one of the aforementioned four, then an exception is thrown.
I used try-catch but for some reason the try and catch aren't recognizing each other unless I place them next to each other which isn't really what I want.
My question is really: Is there a way for my try and catch to recognize each other without being right next to each other, so I can run code in-between them? Or is that impossible and I'm doing it all wrong?
Here's my code so far:
import java.util.*;
public class Calculator
{
public static void main(String[] args)
{
String operatorInput;
double numberInput;
String userRedo = "Y";
double result = 0.0;
Scanner input = new Scanner(System.in);
System.out.println("Type in an arithmetic operator of your choice and press enter.");
System.out.println("Then, please type in a number that will undergo the operation.");
while((userRedo.toUpperCase()).compareTo("Y")==0)
{
try
{
operatorInput = input.nextLine();
if(operatorInput.compareTo("+")!=0||operatorInput.compareTo("-")!=0||
operatorInput.compareTo("*")!=0||operatorInput.compareTo("/")!=0)
{
throw new UnknownOperatorException("Unknown operator!");
}
}
numberInput = input.nextDouble();
if(operatorInput.compareTo("+")==0)
{
result += numberInput;
} else if(operatorInput.compareTo("-")==0)
{
result -= numberInput;
} else if(operatorInput.compareTo("*")==0)
{
result = result * numberInput;
} else
{
result = result / numberInput;
}
System.out.println("\nresult "+operatorInput+" "+numberInput+"= ");
System.out.println("Updated result: "+result);
System.out.println("Again? (y/n)");
userRedo = input.nextLine();
catch(UnknownOperatorException e)
{
System.out.println(e.getMessage());
}
}
}
}
And here's the exception class I made:
public class UnknownOperatorException extends Exception
{
public UnknownOperatorException()
{
super("Please select an actual operator and try again: ");
}
public UnknownOperatorException(String message)
{
super(message);
}
}
They have to be next to each other. There's a few things you could do:
Move the } at the commented line down a ways, like this
while((userRedo.toUpperCase()).compareTo("Y")==0)
{
try
{
operatorInput = input.nextLine();
if(operatorInput.compareTo("+")!=0||operatorInput.compareTo("-")!=0||
operatorInput.compareTo("*")!=0||operatorInput.compareTo("/")!=0)
{
throw new UnknownOperatorException("Unknown operator!");
}
}//this one here
Take that and move it to here
System.out.println("\nresult "+operatorInput+" "+numberInput+"= ");
System.out.println("Updated result: "+result);
}// put it here
Then take these two lines
System.out.println("Again? (y/n)");
userRedo = input.nextLine();
And move them below the catch:
catch(UnknownOperatorException e)
{
System.out.println(e.getMessage());
}
System.out.println("Again? (y/n)");
userRedo = input.nextLine();
}
}
That will let your while loop still sort of function and make your try/catch work. You might need to tweak things a bit to make them work right though
In order for try/catch to work, as Ghost says in a comment, you will need to put them next to each other.
And the code above has some problems...
maybe this works.
public static void main(String[] args) {
String operatorInput=null;
double numberInput;
String userRedo = "Y";
double result = 0.0;
Scanner input = new Scanner(System.in);
System.out.println("Type in an arithmetic operator of your choice and press enter.");
System.out.println("Then, please type in a number that will undergo the operation.");
while ((userRedo.toUpperCase()).compareTo("Y") == 0) {
try {
operatorInput = input.nextLine().trim();
if (operatorInput.compareTo("+") != 0
&& operatorInput.compareTo("-") != 0
&& operatorInput.compareTo("*") != 0
&& operatorInput.compareTo("/") != 0) {
throw new UnknownOperatorException("Unknown operator!");
}
} catch (UnknownOperatorException e) {
System.out.println(e.getMessage());
continue;
}
numberInput = Double.parseDouble(input.nextLine());
if (operatorInput.compareTo("+") == 0) {
result += numberInput;
} else if (operatorInput.compareTo("-") == 0) {
result -= numberInput;
} else if (operatorInput.compareTo("*") == 0) {
result = result * numberInput;
} else {
result = result / numberInput;
}
System.out.println("\nresult " + operatorInput + " " + numberInput + "= ");
System.out.println("Updated result: " + result);
System.out.print("Again? (y/n) : ");
userRedo = input.nextLine();
}
input.close();
}
public class Building implements CarbonFootprint {
//implement 4a
void getCarbonFootprint(){
System.out.println("Kim Byers, CSIS 505, Exception Handling, Assignment1");
//Building display
double Bill;
}
//class variables
double monthlyElectricBill;
double monthlyGasBill;
//constructor
public void Building(double monthlyElectricBill, double monthlyGasBill) {
monthlyElectricBill = ([monthyly Electric Billmonth;
monthlyGasBill = monthlyGasBill;
//Constructor
//set method statements
}
I want to write a program which converts a binary number in a decimal.
Ive found out that the problem is that I cant even get the "catch path".
I also know that I have to change somthing with the char but I absolutely dont get a working solution. Thank you.
import java.util.Scanner;
public class BinaryStringToNumber {
public static void main(String[] args) {
String inputBinaer;
Scanner input = new Scanner(System.in);
System.out.print("Type in a binary number: ");
inputBinaer = input.next();
input.close();
try
{
convert(inputBinaer);
}
catch (NumberFormatException e)
{
System.out.println( "Just numbers!" );
} finally {
System.out.println( "Finally" );
}
}
public static void convert(String inputBinaer) throws NumberFormatException{
char [] puffer;
int dez = 0;
puffer = inputBinaer.toCharArray();
for(int i=0;i<puffer.length;i++){
if(puffer[i]== '1'){
dez = (int) (dez + Math.pow(2, puffer.length-1-i));
}
}
System.out.println("The decimal number is: " + dez);
}
}
To get to the catch block, an exception has to be thrown somewhere. Normally, the Java methods do this for you, but since you are parsing everything yourself, you will have to throw the exception. One way would be to add a throw statement to the convert() method whenever it encounters an invalid digit:
import java.util.Scanner;
public class BinaryStringToNumber {
public static void main(String[] args) {
String inputBinaer;
Scanner input = new Scanner(System.in);
System.out.print("Type in a binary number: ");
inputBinaer = input.next();
input.close();
try
{
convert(inputBinaer);
}
catch (NumberFormatException e)
{
System.out.println( "Just numbers!" );
} finally {
System.out.println( "Finally" );
}
}
public static void convert(String inputBinaer) throws NumberFormatException{
char [] puffer;
int dez = 0;
puffer = inputBinaer.toCharArray();
for(int i=0;i<puffer.length;i++){
if(puffer[i]== '1'){
dez = (int) (dez + Math.pow(2, puffer.length-1-i));
} else if (puffer[i] != '0') {
throw new NumberFormatException("Invalid digit: " + puffer[i]);
}
}
System.out.println("The decimal number is: " + dez);
}
}
You need to specify where do you throw the NumberFormatException. I'd put an if in the for loop where I'd check the char, and if it was not a '0' or a '1', I'd throw an exception. Hope I helped.
You can throw NumberFormatException in case of bad input. That is allowed in Java.