Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

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(); } } } }

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote