[JAVA] Suppose we need to write code that receives String input from a user, and
ID: 3884453 • Letter: #
Question
[JAVA]
Suppose we need to write code that receives String input from a user, and we expect the String input to contain a double value (inside quotes). We want to convert the String to a double using the static method Double.parseDouble(String s) from the Double class. The parseDouble method throws a NumberFormatException if the String s is not a parsable double. Write a method printSum that takes two String parameters (that hopefully have parsable doubles in them), and either prints the sum or prints that the inputs were invalid by handling the exception in a try/catch block and responding accordingly.
Explanation / Answer
Note : Could you please check the output .If you required any changes Just intimate.I will modify it.Thank You.
________________
ParseString.java
import java.util.Scanner;
public class ParseString {
public static void main(String[] args) {
//Declaring variables
String str1, str2;
double result;
/*
* Creating an Scanner class object which is used to get the inputs
* entered by the user
*/
Scanner sc = new Scanner(System.in);
//Getting the strings entered by the user
System.out.print("Enter string#1:");
str1 = sc.next();
System.out.print("Enter string#2:");
str2 = sc.next();
//calling the method by passing the user entered inputs as arguments
try {
result = printSum(str1, str2);
//displaying the sum of two double values
System.out.println("The Sum is :" + result);
} catch (NumberFormatException nfe) {
System.out.println("Exception :" + nfe);
}
}
/* this method will find the double values in the string
* and add those two double values and return it
*/
private static double printSum(String str1, String str2) {
int i, j;
double d1, d2, res = 0.0;
i = (str1.indexOf("'"));
j = str1.indexOf("'", i + 1);
d1 = Double.parseDouble(str1.substring(i + 1, j));
i = (str2.indexOf("'"));
j = str2.indexOf("'", i + 1);
d2 = Double.parseDouble(str2.substring(i + 1, j));
res = d1 + d2;
return res;
}
}
__________________
Output:
Enter string#1:beauti'56.67'ful
Enter string#2:celeb'78.89'rations
The Sum is :135.56
_________________Thank You
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.