Hi, I\'ve been having trouble trying to figure out how to get my code to be able
ID: 3633990 • Letter: H
Question
Hi,
I've been having trouble trying to figure out how to get my code to be able to determine if a string with a decimal value is a double. I'm required to use try/catch with Integer.parseInt and Double.parseDouble.
This is my program:
import java.io.*;
import java.util.Scanner;
//////////////////////////////////////////////////////////////////////////
class Assignment
{
//-----------------------------------------------------------------------------
public static void main (String [] args) throws Exception
{
while(true)
{
Scanner kb = new Scanner(System.in);
System.out.print("Enter a String: ");
String input = kb.nextLine();
try
{
Integer.parseInt(input);
System.out.println(input + " is an int.");
Double.parseDouble(input);
System.out.println(input + " is a double.");
}
catch(NumberFormatException e)
{
System.out.println();
}
}
}
//-----------------------------------------------------------------------------
} // end class Assignment
//////////////////////////////////////////////////////////////////////////
Trying to get the Output to look like this:
Enter a String: 9.8
9.8 is a double.
Any help would be greatly appreciated!
Explanation / Answer
import java.io.*; import java.util.Scanner; import java.lang.*; class Assignment { public static void main (String [] args) throws Exception { while(true) { Scanner kb = new Scanner(System.in); System.out.print("Enter a String: "); String input = kb.nextLine(); try { Integer.parseInt(input); System.out.println(input + " is a integer."); continue; } catch(NumberFormatException e) { System.out.println(); } try { Double.parseDouble(input); System.out.println(input + " is a double."); } catch(NumberFormatException e) { System.out.println(); } } } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.