
So I have an assignment where we have to convert strings into double.I have to modify the method parseDouble() to fully implement the method to imitate the Double.parseDouble() method of Java. In other words, parseDouble() method takes a String as input and converts it into a double when possible and returns it. If the string cannot be converted into a positive double, it returns -1.You will also modify the main method to ask the user to input a positive double in a JoptionPane, then use your parseDouble method (not Java's built-in parseDouble method) to convert it to a double and return twice the value of the input, or a message that the input is not a valid positive number.
and this is my code: I just can't figure out if I did it right or not
import javax.swing.JOptionPane;
public class Parsing {
public static int parseInt(String value) {
int x = 0;
int digit = 0;
for (int i=0; i<value.length(); i++) {
switch (value.charAt(i)) {
case '0':
digit = 0;
break;
case '1':
digit = 1;
break;
case '2':
digit = 2;
break;
case '3':
digit = 3;
break;
case '4':
digit = 4;
break;
case '5':
digit = 5;
break;
case '6':
digit = 6;
break;
case '7':
digit = 7;
break;
case '8':
digit = 8;
break;
case '9':
digit = 9;
break;
default:
return -1;
}
x = x*10 + digit;
}
return x;
}
public static double parseDouble(String value) {
double x = 0;
int digit = 0;
boolean beforeDecimal = true;
int factor = 0;
for (int i=0; i<value.length(); i++) {
switch (value.charAt(i)) {
case '0':
digit = 0;
break;
case '1':
digit = 1;
break;
case '2':
digit = 2;
break;
case '3':
digit = 3;
break;
case '4':
digit = 4;
break;
case '5':
digit = 5;
break;
case '6':
digit = 6;
break;
case '7':
digit = 7;
break;
case '8':
digit = 8;
break;
case '9':
digit = 9;
break;
case '.':
beforeDecimal = false;
break;
default:
return -1;
}
//change the code below
if (beforeDecimal) {
x = x*10 + digit;
}
//else
}
return x;
}
public static void main(String[] args) {
//declare variables
String input;
int x;
// Ask user for an integer
input = JOptionPane.showInputDialog(null,
"Please input a positive integer");
x = parseInt(input);
JOptionPane.showMessageDialog(null,
"Twice of that number is "+ 2*x);
}
}
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.