Java Create Value class that represents the values that can be stored in the nod
ID: 3801163 • Letter: J
Question
Java
Create Value class that represents the values that can be stored in the node class.
A value can be either a double or a string. A separate data field is provided for each so it is possible for a "Value" to contain both a double and a string.
The tag (Which is an enum of STRING, DBL, INVALID) field indicates which of these data fields holds the "real value" of the Value. A Value can also have an "INVALID" tag. Values are constructed with tag STRING, dval 0, and sval a null String.
Write a toString method for Value. Notice that you do not know whether the input will be a double or a string until after it has been entered. To resolve this problem accept the input as a String and check the first character. If it is a double quote mark (") it is a string and copy it (after allocating memory) without the quote mark to the sval field. Otherwise the input is intended as a double. In this case convert it to a double with Double.parseDouble and store the result in the dval field.
Explanation / Answer
JAVA Program :
import java.util.*;
import java.lang.*;
import java.io.*;
class Value{
double dVal = 0;
String sVal = "";
String tag;
@Override
public String toString(){
if(tag.equals("DOUBLE"))return dVal+"";
return sVal;
}
}
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner obj = new Scanner(System.in);
String input = obj.next();
Value v = new Value();
if(input.charAt(0)=='"'){
v.sVal = input.substring(1,input.length());
v.tag = "STRING";
}
else{
v.tag = "DOUBLE";
v.dVal = Double.parseDouble(input);
}
System.out.println(v);
}
}
OUTPUT :
"Hi
Hi
2.58
2.58
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.