Postfix evaluation in java with stack - java

I made this program that evaluates a postfix expression.
It works fine if only single digit numbers are used.
My problem is how do I push multiple-digit numbers if input has spaces?
ex. input: 23+34*- output is -7
but if I input: 23 5 + output is only 3(which is the digit before the space)
it should have an output of 28
my codes:
public class Node2
{
public long num;
Node2 next;
Node2(long el, Node2 nx){
num = el;
next = nx;
}
}
class stackOps2
{
Node2 top;
stackOps2(){
top = null;
}
public void push(double el){
top = new Node2(el,top);
}
public double pop(){
double temp = top.num;
top = top.next;
return temp;
}
public boolean isEmpty(){
return top == null;
}
}
public class ITP {
static stackOps2 so = new stackOps2();
public static final String operator = "+-*/^";
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the infix:");
String s = input.next();
String output;
InToPost theTrans = new InToPost(s);
output = theTrans.doTrans();
System.out.println("Postfix is " + output + '\n');
System.out.println(output+" is evaluated as: "+evaluate(output));
}
public static double evaluate(String value)throws NumberFormatException{
for(int i=0;i<value.length();i++){
char val = value.charAt(i);
if(Character.isDigit(value.charAt(i))){
String v = ""+val;
so.push(Integer.parseInt(v));
}
else if(isOperator(val)){
double rand1=so.pop();
double rand2=so.pop();
double answer ;
switch(val){
case '+': answer = rand2 + rand1;break;
case '-': answer = rand2 - rand1;break;
case '*': answer = rand2 * rand1;break;
case '^': answer = Math.pow(rand2, rand1);break;
default : answer = rand2 / rand1;break;
}
so.push(answer);
}
else if(so.isEmpty()){
throw new NumberFormatException("Stack is empty");
}
}
return so.pop();
}
public static boolean isOperator(char ch){
String s = ""+ch;
return operator.contains(s);
}
}

This is a small, self-contained example that does all the string parsing and evaluation. The only difference from your example is that it accepts the whole string at once instead of using a Scanner. Note the use of Integer.parseInt -- that's missing in your example. I think you can easily extend this for your needs.
#SuppressWarnings({"rawtypes", "unchecked"})
public static void main(String[] args) {
final String in = "5 9 + 2 * 6 5 * +";
final Deque<Object> s = new LinkedList();
for (String t : in.split(" ")) {
if (t.equals("+")) s.push((Integer)s.pop() + (Integer)s.pop());
else if (t.equals("*")) s.push((Integer)s.pop() * (Integer)s.pop());
else s.push(Integer.parseInt(t));
}
System.out.println(s.pop());
}

Related

Calculator for metric distance from an expression that contains different scales

public enum Operator {
PLUS("+"),
MINUS("-");
private final String operator;
Operator(String operator) {
this.operator = operator;
}
public String getOperator() {
return operator;
}
public static Operator getByValue(String operator) {
for (Operator operatorEnum : Operator.values()) {
if (operatorEnum.getOperator().equals(operator)) {
return operatorEnum;
}
}
throw new IllegalArgumentException("Invalid value");
}
}
//////////
public enum MetricConvertor {
m(1000),
cm(10),
mm(1),
km(1000000),
dm(100);
private int scale;
MetricConvertor(int scale) {
this.scale = scale;
}
public int getScale() {
return scale;
}
}
/////////
public class Application {
public static void main(String[] args) {
int scale = MetricConvertor.valueOf("m").getScale();
}
I wan to create a calculator that is capable of computing a metric distance value from an expression that contains different scales and systems.
Output should be specified by the user.
Only Addition and subtraction is allowed.
Output is in lowest unit.
Expression: 10 cm + 1 m - 10 mm
Result: 1090 mm
I am stuck at this point, how can I add or substract the values for a list and convert them at the lowest scale sistem( eg above mm, but it can be dm if are added for example dm + m + km)
Here is solution
split each string by add/minus and add it to appropriate list
split number and metric in each list(can use matcher) and sum it
result = sumAdd - sumMinus(mm).
Please optimize it, because i don't have time to optimize this code, I need to go to bed :D
Result is in mm, so you have to get lowest metric and recaculate it(leave it to you).
private static int caculator(String exp) {
List<String> addList = new ArrayList<>();
List<String> minusList = new ArrayList<>();
int checkPoint = 0;
boolean op = true;//default first value is plus
// Split string with add/minus
for (int i = 1; i < exp.length(); i++) {
String s = exp.substring(i, i + 1);
if (Operator.PLUS.getOperator().equals(s)) {
checkOperator(addList, minusList, op, exp.substring(checkPoint, i).trim());
checkPoint = i + 1;
op = true;
continue;
}
if (Operator.MINUS.getOperator().equals(s)) {
checkOperator(addList, minusList, op, exp.substring(checkPoint, i).trim());
checkPoint = i + 1;
op = false;
continue;
}
}
// Add last string
checkOperator(addList, minusList, op, exp.substring(checkPoint).trim());
// Get sum each list
int sumAdd = sumList(addList);
int sumMinus = sumList(minusList);
return sumAdd - sumMinus;
}
//sum a list
private static int sumList(List<String> addList) {
int sum = 0;
for (String s: addList) {
String[] arr = s.split(" ");
int value = Integer.parseInt(arr[0]);
int scale = MetricConvertor.valueOf(arr[1]).getScale();
sum += value * scale;
}
return sum;
}
// check operator to put into approriate list
private static void checkOperator(List<String> addList, List<String> minusList, boolean op, String substring) {
if (op) {
addList.add(substring);
} else {
minusList.add(substring);
}
}

How to print out a toString for this class?

I have written a polynomial class and a tester class. The polynomial class can evaluate and return the sum of the polynomial when the degree, coefficients and the value of x are provided. Basically I need to edit my toString method so it actually prints out the polynomial
import java.util.Arrays;
import java.util.Scanner;
public class Polynomial {
private int degree;
private int [] coefficient;
private double evaluation;
private double sum;
private double value;
Scanner key = new Scanner(System.in);
public Polynomial(int degree)
{
this.degree = degree;
coefficient = new int [degree+1];
}
public void setCoefficient(int coefficient)
{
this.coefficient[this.degree] = coefficient;
}
public int getCoefficient(int degree)
{
return coefficient[degree];
}
public double Evaluate(double value)
{
this.value =value;
for (int i=0; i<=degree; i++)
{
System.out.println("Enter coefficent for position " + i);
this.coefficient[i] = key.nextInt();
evaluation = Math.pow(value, i)*this.coefficient[0] ;
this.sum += evaluation;
}
return sum;
}
/** Standard toString method */
//needed something better than this below...needed an actual polynomial printed out
public String toString()
{
return "The degree of the polynomial is " + degree + " and the value for which it has been evaluated is" + value;
}
}
This should be along the lines you should be proceeding. I included the main function in your Polynomial class for simplicity, so you will have to modify that if you want to keep it in your tester class. Notice that degree has been made into an integer array of size degree +1(allocated in the constructor):
import java.util.Scanner;
public class Polynomial {
private int degree;
private int [] coefficient;
private double evaluation;
private double sum;
Scanner key = new Scanner(System.in);
public Polynomial(int degree)
{
this.degree = degree;
coefficient = new int [degree+1];
}
public void setCoefficient(int coefficient, int degree)
{
this.coefficient[degree] = coefficient;
}
public int getCoefficient(int degree)
{
return coefficient[degree];
}
public void Evaluate(double value)
{
for (int i=0; i<=degree; i++)
{
System.out.println("Enter coefficent for position " + i);
this.coefficient[i] = key.nextInt();
evaluation = Math.pow(value, i)*this.coefficient[0] ;
this.sum += evaluation;
}
}
public double getSum(){
return sum;
}
public String toString()
{
String s = "";
for (int i=0; i <= degree; i++)
{
s += coefficient[i];
switch (i) {
case 0:
s += " + ";
break;
case 1:
s += "x + ";
break;
default:
s += "x^" + i + ((i==degree)?"":" + ");
}
}
return s;
}
public static void main(String[] args) {
int degree;
double sum;
int coefficient;
Scanner key = new Scanner(System.in);
System.out.println("Enter the degree of the polynomial");
degree=key.nextInt();
Polynomial fun = new Polynomial(degree);
fun.Evaluate(3.0);
System.out.println(" The sum of the polynomial is " + fun.getSum());
System.out.println(fun);
}
}
The usual way of making the objects of a class printable is to supply a toString method in the class, which specifies how to express objects of that class as a String. Methods such as println and other ways of outputting a value will call a class's toString method if they need to print an object of that class.
You should adopt the same pattern with your Polynomial class - write a toString method with all the output logic. Then in your PolynomialTester class, all you need to write is System.out.println(fun); and the rest will just happen. You'll find this far more versatile than writing a method that actually does the printing. For example, you'll be able to write something like
System.out.println("My polynomial is " + fun + " and " + fun + " is my polynomial.");
if that's your idea of fun.
A few other things concern me about your class.
You seem to be only storing one coefficient and one exponent. I'd expect a polynomial to have a whole array of coefficients.
You have fields for evaluation and sum - but these only really make sense while a polynomial is being evaluated. They're not long-term properties of the polynomial. So don't store them in fields. Have them as local variables of the evaluate method, and return the result of the evaluation.
I'd expect a class like this to be immutable. That is, you should provide all the coefficients when the object is created, and just never change them thereafter. If you do it that way, there's no need to write setter methods.
So I've written my own version of your class, that fixes those issues listed above, and implements a toString method that you can use for printing it. A second version of toString lets you specify which letter you want to use for x. I've used "varargs" in the constructor, so you can construct your polynomial with a line such as
Polynomial fun = new Polynomial (7, 2, 5, 0, 1);
specifying the coefficients from the constant term through in order to the coefficient of the term with the highest exponent. Or you can just pass an array.
See that I've changed the logic a wee bit - my version prints the polynomial in the conventional order, from highest to lowest exponent. It leaves off the decimals if the coefficient is an integer. It doesn't print a 1 in front of an x. And it deals cleanly with - signs.
import java.util.Arrays;
public class Polynomial {
private double[] coefficients;
public Polynomial(double... coefficients) {
this.coefficients = Arrays.copyOf(coefficients, coefficients.length);
}
public int getDegree() {
int biggestExponent = coefficients.length - 1;
while(biggestExponent > 0 && coefficients[biggestExponent] == 0.0) {
biggestExponent--;
}
return biggestExponent;
}
public double getCoefficient(int exponent) {
if (exponent < 0 || exponent > getDegree()) {
return 0.0;
} else {
return coefficients[exponent];
}
}
public double evaluateAt(double x) {
double toReturn = 0.0;
for (int term = 0; term < coefficients.length; term++) {
toReturn += coefficients[term] * Math.pow(x, term);
}
return toReturn;
}
#Override
public String toString() {
return toString('x');
}
public String toString(char variable) {
boolean anythingAppendedYet = false;
StringBuilder toReturn = new StringBuilder();
for (int exponent = coefficients.length - 1; exponent >= 0; exponent--) {
if (coefficients[exponent] != 0.0) {
appendSign(toReturn, exponent, anythingAppendedYet);
appendNumberPart(toReturn, exponent);
appendLetterAndExponent(toReturn, exponent, variable);
anythingAppendedYet = true;
}
}
if (anythingAppendedYet) {
return toReturn.toString();
} else {
return "0";
}
}
private void appendSign(StringBuilder toAppendTo, int exponent, boolean anythingAppendedYet) {
if (coefficients[exponent] < 0) {
toAppendTo.append(" - ");
} else if (anythingAppendedYet) {
toAppendTo.append(" + ");
}
}
private void appendNumberPart(StringBuilder toAppendTo, int exponent) {
double numberPart = Math.abs(coefficients[exponent]);
if (numberPart != 1.0 || exponent == 0) {
//Don't print 1 in front of the letter, but do print 1 if it's the constant term.
if (numberPart == Math.rint(numberPart)) {
// Coefficient is an integer, so don't show decimals
toAppendTo.append((long) numberPart);
} else {
toAppendTo.append(numberPart);
}
}
}
private void appendLetterAndExponent(StringBuilder toAppendTo, int exponent, char variable) {
if (exponent > 0) {
toAppendTo.append(variable);
}
if (exponent > 1) {
toAppendTo.append("^");
toAppendTo.append(exponent);
}
}
}
So I tested it with this class
public class PolynomialTester {
public static void main(String[] args) {
Polynomial fun = new Polynomial (7, 2, 5, 0, 1);
System.out.println(fun.getDegree());
System.out.println(fun.evaluateAt(3));
System.out.println(fun);
}
}
and the output was
4
139.0
x^4 + 5x^2 + 2x + 7
then I realised that you wanted to be able to input the coefficients in a loop. So I changed PolynomialTester to this. See how I build the array and then create the object.
import java.util.Scanner;
public class PolynomialTester {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the degree:");
int degree = input.nextInt();
double[] coefficients = new double[degree + 1];
for( int exponent = 0; exponent <= degree; exponent++) {
System.out.println("Enter the coefficient of x^" + exponent);
coefficients[exponent] = input.nextDouble();
}
Polynomial fun = new Polynomial (coefficients);
System.out.println(fun.evaluateAt(3));
System.out.println(fun);
input.close();
}
}
Note that if you really want your polynomial to be printed in "reverse" order, with the constant term first, you could change the loop in the toString method to this.
for (int exponent = 0; exponent < coefficients.length; exponent++) {
You may add a class member String poly, then modify the following method.
public void Evaluate(double value)
{
for (int i=0; i<=degree; i++)
{
System.out.println("Enter coefficent for position " + i);
this.coefficient= key.nextInt();
evaluation = Math.pow(value, i)*coefficient ;
this.sum += evaluation;
this.poly = "";
if(coefficient != 0)
{
if(i > 0)
{
this.poly += " + " + Integer.toString(coefficient) + "x^" + Integer.toString(i); // you may replace x with the actual value if you want
}
else
{
this.poly = Integer.toString(coefficient)
}
}
}
}

What is Java Error: 93: Reached end of file while parsing?

This may be a relatively simple question, but why is my program getting this error:Expression.java:93: error: reached end of file while parsing
}
I have tried following multiple guides online, like opening and closing my classes correctly, but unfortunately I still seem to be getting this error.
Here is my code in case this helps:
public class Expression {
private static final String SPACE = " ";
private static final String PLUS = "+";
private static final String MINUS = "-";
public static int rank(String operator) {
switch (operator) {
case "^": //5
return 3;
case "*":
case "/":
return 2;
case PLUS:
case MINUS: //2
return 1;
default:
return -1;
}
}
public static boolean isOperator(String token) { //4
if (rank(token) > 0){
return true;
}
return false;
}
public static int applyOperator(String operator,int op1,int op2){ //7
switch (operator) {
case PLUS:
return op1+op2;
case MINUS:
return op1-op2;
case "*":
return op1*op2;
case "/":
return op1/op2;
default:
return -1;
}
}
public static String toPostfix(String infixExpr) {
StringBuilder output = new StringBuilder();
Stack<String> operators = new ArrayStack<>();
for (String token: infixExpr.split("\\s+")) {
if (isOperator(token)) { // operator //4
// pop equal or higher precedence
while (!operators.isEmpty() &&
rank(operators.peek()) >= rank(token)) {
output.append(operators.pop() + SPACE);
}
operators.push(token);
} else { // operand
output.append(token + SPACE);
}
}
while (!operators.isEmpty()) {
output.append(operators.pop() + SPACE);
}
return output.toString();
}
public class PostFixTest {
public static int evalPostfix(String infixExpr) {
Stack <String> s = new ArrayStack<String>();
String operand = null;
for(int i = 0; i < infixExpr.length(); i++) {
if (Character.isDigit(infixExpr.charAt(i)))
s.push(infixExpr.charAt(i) + "");
else {
if (s.size() > 1) {
int value1 = Integer.parseInt(s.pop());
int value2 = Integer.parseInt(s.pop());
s.push(applyOperator(infixExpr.charAt(i) + "", value1, value2) + "");
}
}
}
return s.pop();
}
}
public static void main(String[] args) {
System.out.println(rank("/"));
String infix = "a * b * c + d ^ e / f";
System.out.println(toPostfix(infix));
System.out.print("Using applyOperator method, 7 * 3 = ");
System.out.println(applyOperator("*", 3, 7));
System.out.print("Using applyOperator method, 50 + 12 = ");
System.out.println(applyOperator("+", 50, 12));
}
You are losing right } in your code last. like:
...
public static void main(String[] args) {
System.out.println(rank("/"));
String infix = "a * b * c + d ^ e / f";
System.out.println(toPostfix(infix));
System.out.print("Using applyOperator method, 7 * 3 = ");
System.out.println(applyOperator("*", 3, 7));
System.out.print("Using applyOperator method, 50 + 12 = ");
System.out.println(applyOperator("+", 50, 12));
}
} // you lost this bracket.

Cannot convert an ArrayList with my custom object as its data type into the corresponding regular array

As the title says, I cannot convert my ArrayList into an Array. The data type of my ArrayList is a custom object but I cannot seem to find what my problem is. The error that it gives doesn't show up as a problem until the program is run. The first two classes are the objects, then I have a class calle Tester where the main method is.
Class where error appears:
package backend;
import java.util.ArrayList;
public class Function {
Coefficient[] coefArray;
int constant;
public Function(ArrayList<Coefficient> coefFunction, int constant){
Coefficient[] coefArray = (Coefficient[]) coefFunction.toArray();
this.coefArray = sortArray(coefArray);
this.constant = constant;
}
private Coefficient[] sortArray(Coefficient[] newArray){
int tempPow = -1000000000;
Coefficient[] sortedArray = new Coefficient[newArray.length];
sortedArray = null;
for(int i=0; isFull(sortedArray); i++){
for(Coefficient coef : newArray){
if(coef.pow>tempPow){
tempPow = coef.pow;
sortedArray[i] = coef;
}
}
}
return sortedArray;
}
private boolean isFull(Coefficient[] anArray){
for(Coefficient i : anArray) {
if(i == null) return true;
}
return false;
}
public String toString(){
String compiledString="";
for(Coefficient coef : coefArray){
compiledString += coef.toString()+"+";
}
if(constant==0){
//No constant there
}else{
compiledString = compiledString + constant;
}
return compiledString;
}
}
Coefficient Class:
package backend;
public class Coefficient {
String stringVersion;
public int pow;
public int coefInteger;
public double coefDouble;
//Constructor for variable with a coefficient that is non-fractal and a power higher than 1
public Coefficient(int coef, int pow){
this.coefInteger = coef;
this.pow = pow;
switch(coef){
case 0:
//Do nothing here
case 1:
this.stringVersion = "x^"+pow;
break;
default:
this.stringVersion = coef+"x^"+pow;
break;
}
}
//Constructor for variable with a coefficient that is fractal and a power higher than 1
public Coefficient(double coef, int pow){
this.coefDouble = coef;
this.pow = pow;
this.stringVersion = coef+"x^"+pow;
}
//Constructor for variable with a coefficient but no power
public Coefficient(double coef){
this.coefDouble = coef;
this.pow = 1;
this.stringVersion = coef+"x";
}
//Constructor for variable with a coefficient but no power
public Coefficient(int coef){
this.coefInteger = coef;
this.pow = 1;
this.stringVersion = coef+"x";
}
public String toString(){
return stringVersion;
}
}
Tester:
package backend;
import java.util.ArrayList;
import java.util.Scanner;
public class Tester {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
ArrayList<Coefficient> function = new ArrayList<Coefficient>();
Coefficient xVal;
Function printFunction;
System.out.println("Enter the degree of the equation:");
int pow = scan.nextInt();
System.out.println("Enter the x components of the function in the order of coefficient then power. Enter constant last:");
double coef = 0;
while(pow>0){
coef = scan.nextDouble();
if(pow==1){
if((int) coef == coef){
xVal = new Coefficient((int) coef);
}else{
xVal = new Coefficient(coef);
}
}else{
if((int) coef == coef){
xVal = new Coefficient((int) coef, pow);
}else{
xVal = new Coefficient(coef, pow);
}
}
function.add(xVal);
pow--;
}
System.out.println("Enter the constant:");
printFunction = new Function(function, scan.nextInt());
System.out.println(printFunction.toString());
}
}
Error:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object;
cannot be cast to [Lbackend.Coefficient;
at backend.Function.<init>(Function.java:11)
at backend.Tester.main(Tester.java:36)
Any and all help is greatly appreciated. If you see something else that needs to be fixed, please point it out.
The error is in this line:
Coefficient[] coefArray = (Coefficient[]) coefFunction.toArray();
If you read the javadoc of toArray(), you can see that it returns an Object[], which you cannot simply cast to Coefficient[].
Instead use toArray(T[] a):
Coefficient[] coefArray = coefFunction.toArray(new Coefficient[coefFunction.size()]);
Disclaimer: I did not review the rest of your code, so the absence of any remarks does not imply that everything else is fine.

Roman Numeral to Number Conversion [duplicate]

This question already has answers here:
Converting Roman Numerals To Decimal
(30 answers)
Closed 9 years ago.
Trying to write program to read in a string of characters that represent a Roman numeral (from user input) and then convert it to Arabic form (an integer). For instance, I = 1, V = 5, X = 10 etc.
Basically, the constructor that takes a parameter of type String must interpret the string (from user input) as a Roman numeral and convert it to the corresponding int value.
Is there an easier way to solve this besides the below in progress (which isn't compiling as yet):
import java.util.Scanner;
public class RomInt {
String roman;
int val;
void assign(String k)
{
roman=k;
}
private class Literal
{
public char literal;
public int value;
public Literal(char literal, int value)
{
this.literal = literal;
this.value = value;
}
}
private final Literal[] ROMAN_LITERALS = new Literal[]
{
new Literal('I', 1),
new Literal('V', 5),
new Literal('X', 10),
new Literal('L', 50),
new Literal('C', 100),
new Literal('D', 500),
new Literal('M', 1000)
};
public int getVal(String s) {
int holdValue=0;
for (int j = 0; j < ROMAN_LITERALS.length; j++)
{
if (s.charAt(0)==ROMAN_LITERALS[j].literal)
{
holdValue=ROMAN_LITERALS[j].value;
break;
} //if()
}//for()
return holdValue;
} //getVal()
public int count()
{
int count=0;
int countA=0;
int countB=0;
int lastPosition = 0;
for(int i = 0 ; i < roman.length(); i++)
{
String s1 = roman.substring(i,i+1);
int a=getVal(s1);
countA+=a;
}
for(int j=1;j<roman.length();j++)
{
String s2= roman.substring(j,j+1);
String s3= roman.substring(j-1,j);
int b=getVal(s2);
int c=getVal(s3);
if(b>c)
{
countB+=c;
}
}
count=countA-(2*countB);
return count;
}
void disp()
{
int result=count();
System.out.println("Integer equivalent of "+roman+" = " +result);
}
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter Roman Symbol:");
String s = keyboard.nextLine();
RomInt();
}
}
Roman numerals/Decode Example:
class Roman {
private static int decodeSingle(char letter) {
switch (letter) {
case 'M':
return 1000;
case 'D':
return 500;
case 'C':
return 100;
case 'L':
return 50;
case 'X':
return 10;
case 'V':
return 5;
case 'I':
return 1;
default:
return 0;
}
}
public static int decode(String roman) {
int result = 0;
String uRoman = roman.toUpperCase(); //case-insensitive
for (int i = 0; i < uRoman.length() - 1; i++) {//loop over all but the last character
if (decodeSingle(uRoman.charAt(i)) < decodeSingle(uRoman.charAt(i + 1))) {
result -= decodeSingle(uRoman.charAt(i));
} else {
result += decodeSingle(uRoman.charAt(i));
}
}
result += decodeSingle(uRoman.charAt(uRoman.length() - 1));
return result;
}
public static void main(String[] args) {
System.out.println(decode("MCMXC")); //1990
System.out.println(decode("MMVIII")); //2008
System.out.println(decode("MDCLXVI")); //1666
}
}
Use enum, for easy and simple solution. At first define the decimal equivalent weight at roman.
enum Roman{
i(1),iv(4),v(5), ix(9), x(10);
int weight;
private Roman(int weight) {
this.weight = weight;
}
};
This is the method to convert decimal to roman String.
static String decToRoman(int dec){
String roman="";
Roman[] values=Roman.values();
for (int i = values.length-1; i>=0; i--) {
while(dec>=values[i].weight){
roman+=values[i];
dec=dec-values[i].weight;
}
}
return roman;
}
You can try using a Hashmap to store the roman numerals and equivalent arabic numerals.
HashMap test = new HashMap();
test.add("I",1);
test.add("V",5);
test.add("X",10);
test.add("L",50);
test.add("C",100);
test.add("D",500);
test.add("M",1000);
//This would insert all the roman numerals as keys and their respective arabic numbers as
values.
To retrieve respective arabic numeral one the input of the user, you can use following peice of code:
Scanner sc = new Scanner(System.in);
System.out.println(one.get(sc.next().toUpperCase()));
//This would print the respective value of the selected key.This occurs in O(1) time.
Secondly,
If you only have these set of roman numerals, then you can go for simple switch case statement.
switch(sc.next().toUpperCase())
{
case 'I' :
System.out.println("1");
break;
case 'V'
System.out.println("5");
break;
.
.
.
& so on
}
Hope this helps.
How about this:
public static int convertFromRoman(String roman) {
Map<String, Integer> v = new HashMap<String, Integer>();
v.put("IV", 4);
v.put("IX", 9);
v.put("XL", 40);
v.put("CD", 400);
v.put("CM", 900);
v.put("C", 100);
v.put("M", 1000);
v.put("I", 1);
v.put("V", 5);
v.put("X", 10);
v.put("L", 50);
v.put("D", 500);
int result = 0;
for (String s : v.keySet()) {
result += countOccurrences(roman, s) * v.get(s);
roman = roman.replaceAll(s, "");
}
return result;
}
public static int countOccurrences(String main, String sub) {
return (main.length() - main.replace(sub, "").length()) / sub.length();
}
Not sure I've got all possible combinations as I'm not an expert in roman numbers. Just make sure that the once where you substract come first in the map.
Your compilation issue can be resolved with below code. But surely its not optimized one:
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter Roman Symbol:");
String s = keyboard.nextLine();
RomInt temp = new RomInt();
temp.getVal(s);
temp.assign(s);
temp.disp();
}

Categories

Resources