A Program With StringTokenizer in Java [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I wrote a simple calculation program. I want users to enter their request as 12+12 and return the answer. I used StringTokenizer, but I got an error and it doesn't show me any result. There was a mention that Calc is a superclass and MinusCalc and PlusCalc are subclasses. Does anyone have any idea?
void inputLineData() { // This is just the function that use for this case
System.out.println(" Plz enter your all numbers");
String strAll = key.next();
StringTokenizer st = new StringTokenizer(strAll);
int n1 = Integer.parseInt(st.nextToken());
String str = st.nextToken();
int n2 = Integer.parseInt(st.nextToken());
switch (str.charAt(0)) {
case '+':
PlusCalc P = new PlusCalc(n1, n2);
listCalc[indexCalc] = P;
indexCalc++;
break;
case '-':
MinusCalc M = new MinusCalc(n1, n2);
listCalc[indexCalc] = M;
indexCalc++;
break;
default:
System.out.println("Error!");
}
}
And this is MinusCalc class:
public class MinusCalc extends Calc {
#Override
public int func(){
return n1 - n2 ;
}
public MinusCalc(int n1, int n2) {
super(n1, n2);
}
}
And this is PlusCalc class:
public class PlusCalc extends Calc {
#Override
public int func(){
return n1 + n2;
}
public PlusCalc(int n1, int n2) {
super(n1, n2);
}
}
And this is Calc class:
public abstract class Calc {
public Calc(int n1, int n2) { // constructor with parameters!!
this.n1 = n1;
this.n2 = n2;
}
int n1,n2;
public abstract int func();
}

Assuming your input is correct the following might help you (if you have more operators just append to the list). The true in the parameter means you want to use the given operator as a delimiter as well as an operator, meaning it will be returned as a token too.
StringTokenizer st = new StringTokenizer(strAll, "+-*/", true);
if (st.countTokens() == 3) {
int operand1 = Integer.parseInt(st.nextToken().trim());
String operator = st.nextToken();
int operand2 = Integer.parseInt(st.nextToken().trim());
switch (operator.charAt(0)) {
case '+':
PlusCalc P = new PlusCalc(operand1, operand2);
listCalc[indexCalc] = P;
indexCalc++;
break;
case '-':
MinusCalc M = new MinusCalc(operand1, operand2);
listCalc[indexCalc] = M;
indexCalc++;
break;
default:
System.out.println("Error!");
}
}
NOTE: try to use another option mentioned in the comments instead of StringTokenizer if you have not to.

Related

why is calculator.getValue() always 0?

I am a java student and I am working to make my code more object oriented. I can easily code calculator in main but I'm really struggling to implement it with methods. The following code will always return 0...but the goal is to create a program which allows a user to enter an operator and a number in one line (example +5) the code should output the previous value, the new value, and allow for resetting. I believe I am really close to solving this and just need a point in the right direction..
output
Enter an operator and a number:
+5
0.0
Calculator class
import java.util.Scanner;
public class Calculator {
private final int RESET = 0;
private double number = 0;
private double result = 0; // I believe this is the issue but how can I resolve it?
private char operator;
private static Scanner keyboard = new Scanner(System.in);
public Calculator(double number)
{
this.number = number;
}
// this method invokes the whatOperator() to create a new result
// the edited method still returns 0
public double aResult(Calculator other)
{
other.whatOperator();
this.result = other.result;
return result;
}
// I created this method in hopes that it would do most of the work..when I invoke it and enter my operator and number it does not seem to function correctly
public void whatOperator()
{
String operator = null;
operator = enterNumber();
double theNumber = Double.parseDouble(operator);
char theOperator =operator.charAt(0);
operator = null;
operator += theOperator;
// switch method to find the operator
switch(operator){
case "*":
result = getNumber() * theNumber;
break;
case "/":
result = getNumber() / theNumber;
break;
case "+":
result = getNumber() + theNumber;
break;
case "-":
result = getNumber() - theNumber;
break;
case "R":
result = RESET;
break;
}
}
// methods for operation...I was hoping to not use these
public double add(double secondNumber)
{
result = number + secondNumber;
return result;
}
public double divide(double secondNumber)
{
result = number / secondNumber;
return result;
}
public double multiply(double secondNumber)
{
result = number * secondNumber;
return result;
}
public void subtract(double secondNumber)
{
result = number - secondNumber;
}
public double getNumber()
{
return number;
}
// method for getting input
public static String enterNumber()
{
System.out.println("Enter an operator and a number:");
String toString = keyboard.nextLine();
return toString;
}
public static void main (String[] args) {
// the calculator is initialized at 0
Calculator a = new Calculator(0);
// now I create a second calculator with the result from the aResult()
Calculator b = new Calculator(a.aResult(a));
// why is b.getNumber() = 0 at this point?
String theString = String.valueOf(b.getNumber());
// prints 0 every time
System.out.println(theString);
}
}
There are some mistakes in your code.
public double aResult(Calculator other)
{
other = new Calculator(getNumber());
other.whatOperator();
this.result = result;
return result;
}
The line this.result = result doesn't make any sense. I think you wanted the method whatOperator() to return a result e.g.
this.result = other.whatOperator();
I also think that you don't want to override the "other" calculator. You never use the new calculator. But you want to print the output of the new calculator in your main method. Because you never used the new calculator, the output is 0.
In your aResult method you are initiating another new instance of Calculator
public double aResult(Calculator other) {
//other = new Calculator(getNumber()); // this should not be here
other.whatOperator();
this.result = result;
return result;
}
The solution to the problem:
//change
this.result = result; //this does nothing
//to
this.result = other.result; //this changes the result to the new value
//erase this line
other = new Calculator(getNumber()); // do not need to create a new calculator
change the method whatOperator to a double and return a double with it

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.

Java method name error [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
When i try to compile this code i get this error:
dn09.java:38: error: illegal start of expression
public Tip[] preberi (Scanner sc) {
^ dn09.java:38: error: ';' expected
public Tip[] preberi (Scanner sc) {
^ dn09.java:38: error: ';' expected
public Tip[] preberi (Scanner sc) {
^ 3 errors
[Napaka | process.javac]: Object reference not set to an instance of an object.
This is the line of code in the question:
public Tip[] preberi(Scanner sc) {
Tip[] tipi = new tipi[d];
for (int i = 0; i < tipi.length; i++) {
String tip = sc.next();
switch (tip) {
case "prim":
tipi[i] = new Prim(sc.nextInt());
break;
case "arr":
tipi[i] = new Arr(sc.nextInt(), sc.nextInt());
break;
case "ostruct":
break;
case "pstruct":
break;
}
}
return tipi;
}
I have my Scanner declared up in the main() method, it is imported and everything.
As some of you asked this is my whole code(it isnt in working state at all, as you will also see im a beginner so its preety simple.
public class dn09 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int b = sc.nextInt();
int d = sc.nextInt();
Tip[] tipi = preberi(sc);
int u = sc.nextInt();
int[] ukazi = new int[u];
for (int i = 0; i < u; i++) {
ukazi[i] = sc.nextInt(); //if you know a better way to store 2 numbers where i could then
//use the numbers separately that would be super helpfull as id
} //need it for 2 switch statements which im currenty trying to
for (int i = 0; i < u; i++) {//fit into 1.
switch(ukazi[i]) {
case 11:
break;
case 12:
break;
case 13:
break;
case 21:
break;
case 22:
break;
case 23:
break;
case 31:
break;
case 32:
break;
case 33:
break;
}
}
public Tip[] preberi(Scanner sc) {
Tip[] tipi = new tipi[d];
for (int i = 0; i < tipi.length; i++) {
String tip = sc.next();
switch (tip) {
case "prim":
tipi[i] = new Prim(sc.nextInt());
break;
case "arr":
tipi[i] = new Arr(sc.nextInt(), sc.nextInt());
break;
case "ostruct":
break;
case "pstruct":
break;
}
}
return tipi;
}
}
private static class Prim extends dn09 {
protected int v;
public static Prim (int v) {
this.v = v;
}
}
private static class Arr extends dn09 {
protected int n;
protected int t;
public static Arr (int n, int t) {
this.t = t;
this.n = n;
}
}
}
Your main() method needs a closing } you only close the loop and switch.
You also need to remove the two static from your inner classes constructors (Prim(int) and Arr(int,int)). There is a dangling } at the end, perhaps you want to remove the one which closes it?
If you use an IDE and auto-indent the code, those problems get quickly visible.
public class dn09 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int b = sc.nextInt();
int d = sc.nextInt();
Tip[] tipi = preberi(sc);
int u = sc.nextInt();
int[] ukazi = new int[u];
for (int i = 0; i < u; i++) {
ukazi[i] = sc.nextInt(); //if you know a better way to store 2 numbers where i could then
//use the numbers separately that would be super helpfull as id
} //need it for 2 switch statements which im currenty trying to
for (int i = 0; i < u; i++) {//fit into 1.
switch(ukazi[i]) {
case 11:
break;
...
}
}
}
public Tip[] preberi(Scanner sc) {
Tip[] tipi = new tipi[d];
for (int i = 0; i < tipi.length; i++) {
String tip = sc.next();
switch (tip) {
case "prim":
liki[i] = new Prim(sc.nextInt());
break;
...
}
}
return tipi;
}
private static class Prim extends dn09 {
protected int v;
public Prim (int v) {
this.v = v;
}
}
private static class Arr extends dn09 {
protected int n;
protected int t;
public Arr (int n, int t) {
this.t = t;
this.n = n;
}
}
}

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

Postfix evaluation in java with stack

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

Categories

Resources