How to call linked list without array implementation? - java

For this assignment, I write a program, which will calculate the results of Reverse Polish expressions that are provided by the user.
I must use a linked list to maintain the stack for this program (array implementations of the stack will not receive full credit).
I must handle the following situations (errors):
Too many operators (+ - / *)
Too many operands (doubles)
Division by zero
The program will take in a Polish expression that separates the operators and operands by a single space, and terminates the expression with an equals sign.
The program will continue to take and evaluate expressions until the user enters a zero (0) on a line by itself followed by a new line.
my sample output should show the handling of all the error conditions as well as make use of all of the operators. But when I execute the program it says
Error: Main method not found in class program1.Program1, please define the main method as:
public static void main(String[] args)
Java Result: 1
I have no idea how to call linked list without array implementations. Also
RefObject class and TryparseHelper are below in the same package. tnx
package program1;
import java.util.*;
import java.lang.IllegalStateException;
public class Program1 {
public class Node<T>
{
public T Data;
public Node<T> Next;
}
public class Stack<T>
{
private Node<T> top = null;
public final void Push(T value)
{
top = new Node<T>();
top.Data = value;
top.Next = top;
}
public final T Pop()
{
if (top == null)
{
throw new IllegalStateException("Cannot pop if the stack is empty.");
}
T topValue = top.Data;
top = top.Next;
return topValue;
}
public final boolean IsEmpty()
{
return top == null;
}
public final void Clear()
{
top = null;
}
}
public class ReversePolishCalculator
{
public final void Calculator()
{
String expression = "";
while (!expression.equals("0"))
{
System.out.print("Enter expression: ");
expression = new Scanner(System.in).nextLine();
try
{
System.out.println(" = " + Calculate(expression));
}
catch (RuntimeException ex)
{
System.err.println(ex.getMessage());
}
}
}
private Stack<Double> stack = new Stack<Double>();
private double Calculate(String expression)
{
double result = 0.0;
stack.Clear();
String[] tokens = expression.split("[ ]", -1);
for (String token : tokens)
{
double value = 0;
RefObject<Double> tempRef_value = new RefObject<Double>(value);
if (TryParseHelper.tryParseDouble(token, tempRef_value))
{
value = tempRef_value.argValue;
stack.Push(value);
}
else
{
value = tempRef_value.argValue;
DoOperation(token);
}
}
if (!stack.IsEmpty())
{
result = stack.Pop();
}
if (!stack.IsEmpty())
{
throw new IllegalStateException("Too many operands.");
}
return result;
}
private void DoOperation(String token)
{
if (stack.IsEmpty())
{
throw new IllegalStateException("Too many operators.");
}
double rhs = stack.Pop();
if (stack.IsEmpty())
{
throw new IllegalStateException("Too many operators.");
}
double lhs = stack.Pop();
switch (token)
{
case "+":
stack.Push(lhs + rhs);
break;
case "-":
stack.Push(lhs - rhs);
break;
case "*":
stack.Push(lhs * rhs);
break;
case "/":
if (rhs == 0.0)
{
throw new IllegalStateException("Divide by zero.");
}
stack.Push(lhs / rhs);
break;
default:
throw new IllegalStateException("Unexpected operator: " + token);
}
}
}
}
package program1; TryParseHelper
/**
*
* #author David
*/
public final class TryParseHelper
{
public static boolean tryParseInt(String s, RefObject<Integer> result)
{
try
{
result.argValue = Integer.parseInt(s);
return true;
}
catch (NumberFormatException e)
{
return false;
}
}
public static boolean tryParseShort(String s, RefObject<Short> result)
{
try
{
result.argValue = Short.parseShort(s);
return true;
}
catch (NumberFormatException e)
{
return false;
}
}
public static boolean tryParseLong(String s, RefObject<Long> result)
{
try
{
result.argValue = Long.parseLong(s);
return true;
}
catch (NumberFormatException e)
{
return false;
}
}
public static boolean tryParseByte(String s, RefObject<Byte> result)
{
try
{
result.argValue = Byte.parseByte(s);
return true;
}
catch (NumberFormatException e)
{
return false;
}
}
public static boolean tryParseDouble(String s, RefObject<Double> result)
{
try
{
result.argValue = Double.parseDouble(s);
return true;
}
catch (NumberFormatException e)
{
return false;
}
}
public static boolean tryParseFloat(String s, RefObject<Float> result)
{
try
{
result.argValue = Float.parseFloat(s);
return true;
}
catch (NumberFormatException e)
{
return false;
}
}
public static boolean tryParseBoolean(String s, RefObject<Boolean> result)
{
try
{
result.argValue = Boolean.parseBoolean(s);
return true;
}
catch (NumberFormatException e)
{
return false;
}
}
}
package program1; RefObj
/**
*
* #author David
*/
public final class RefObject<T>
{
public T argValue;
public RefObject(T refArg)
{
argValue = refArg;
}
}

As the error message you've pasted says: To run your program, add to Program1 class a method with this signature public static void main(String[] args). Write in it the code you want to run, e.g., System.out.println("hi"); or whatever.
Update: As I understood from your comment, it seems like your problem is trying to call a non-static method Calculator() from main(...). First, you need a background on class vs object and static vs non-static.
A class is a template or a blueprint. An object is an instantiation of that blueprint. For example, a description of a car is a class, any car is an object. Another example is your Stack class and the Stack<Double> stack = new Stack<Double>() object you've used to calculate an expression.
When you call pop() it needs a specific stack to run on. A specific object. For example, you could have 2 stacks at the same time, and calling pop() on one of them shouldn't affect the other. That's why the method pop() is non-static.
Now, let's think of the Program1 class: Are you really thinking of creating multiple program1 and running them/calling their methods in your code? And would each program1 have a different state from the other? Each stack could have different contents at any time, but program1 doesn't really have any content or state.
When you have a method that doesn't depend on any specific object or a particular state, you mark it as static. For example, a method that adds 2 numbers should be static. Same goes for your Calculator() method.
So, back to your question, to call non-static method Calculator() from main(...), you'll either have to:
(1) convert Calculator() into a static method. You need to ask yourself "Is this method related only to a specific instance, a specific object?". For example, the pop() method of Stack is very related to a certain stack object. If you call it on 2 stack objects, it'll give different results. That's why it should be a non-static method, i.e., a method that depends on a particular instance.
However, Calculator() seems like a method that doesn't really depend on anything else. The fact that it uses a member variable called stack is accidental. You can move the stack variable inside Calculator(). Or you could just make stack static as well.
(2) You could, although it wouldn't make much sense, create an instance of Program1 then call Calculator() on it.
I know the difference between class and object, and static and non-static, can be confusing in the beginning. Read more on it, you'll get comfortable with it with time.
For the without-arrays question: If I understand correctly, you have a problem with the array in main(String[] args). The array here is a must for the program to run and is not related to the stack's implementation. So, I don't expect you teacher to mind having it.
Finally, note that the code, I think, has some problems so don't expect it to run from the first time. And that's absolutely normal, and you'll need to know how to trace a code. Good luck!

Related

intellij idea structural search and replace - find all methods that call an api

I'm trying to find all methods in a large java project in which a specific static api is called, and then add an annotation those methods.
The methods can have arbitrary complexity. It can be a simple MyAPI.method("foo");, but it can be also try(Int result = MyAPI.AnotherMethod("foo")) { }. It can be nested inside of a code block, in a lambda expression, anywhere.
The best I have been able to create is this:
class $_1$ {
$ReturnType$ $Method$ /* count 1 to inf */ ($ParameterType$ $Parameter$ /* count 0 to inf */)
{
$stmt1$; /* count 0 to inf */
MyAPI.$MethoddCall$($param$ /* count 0 to inf */);
$stmt2$; /* count 0 to inf */
}
}
This finds some usages, but generally only the simplest one. In the example class bellow, it finds only usage1 (a,b,c) and usage5. Other examples are skipped. Is it even possible to write such a general search, or would I need to tailor it to all possible cases?
The point is, the api is used in thousands of methods and every and each has to be annotated, so I'm looking for anything that will mean I don't have to do it by hand. Worst case, I would try luck with awk, but that would mess up with the crazy CVS we are using, so I prefer Idea solution.
Now an example:
import java.io.PrintWriter;
public class SearchAndReplaceTest
{
private static class MyAPI
{
public static void foo(String x)
{}
public static int bar(String x)
{
return 1;
}
public static int baz(String x, int y)
{
return 1;
}
public static PrintWriter guu(String x)
{
return null;
}
}
public void usage1a()
{
MyAPI.foo("aaaa");
}
public void usage1b()
{
MyAPI.baz("aaaa", 1+1);
}
public void usage1c()
{
MyAPI.baz("aaaa", (1+1)-1);
}
private static int usage2(String xxxx) throws Exception
{
new String();
if(MyAPI.bar("x") == 1)
{}
return 0;
}
private void usage3a(String xxxx) throws Exception
{
new String();
if(1 == 1)
{
MyAPI.baz("xxx", (10+3) - 1);
}
}
private void usage3b(String xxxx) throws Exception
{
new String();
if(1 == 1)
{
MyAPI.foo("xxx");
}
}
private static void usage4(String xxxx) throws Exception
{
new String();
try(PrintWriter x = MyAPI.guu("x"))
{}
catch (Exception e){}
}
public void usage5()
{
new String();
MyAPI.foo("aaaa");
if(1==0)
{}
}
}
I have found out how to do it. Rather than trying to utilize Structural Search's power, I have to search the body of a function only by a script. So the search is for:
class $_1$ {
$ReturnType$ $Method$ ($ParameterType$ $Parameter$);
}
With those constraints:
$Parameter$ // count: [0, inf]
$Method$ // count: [1, inf], text: [x] within hierarchy, script: Method.getText().contains("MyAPI")

Cannot infer type arguments for Generic Class

I am trying to create Expression Tree using the Postfix Expression.
This needs a Stack which could hold Tree Objects.
I created a generic Stack class which could except <TreeTemp> as type argument.
On trying to initialize the stack with following statement, its giving "Cannot infer type arguments for TreeStack<>" error.
private TreeStack<TreeTemp> stack1 = new TreeStack<>(new TreeTemp());
Stack Class:
public class TreeStack<T> {
private T [] stackElem;
private final int MAXSTACKSIZE;
private int top;
public TreeStack(Class<T> t) {
top = -1;
MAXSTACKSIZE = 20;
final T[] stackElem = (T[]) Array.newInstance(t, MAXSTACKSIZE);
this.stackElem = stackElem;
}
public void push(T elem) throws Exception{
if(isFull()) {
stackElem[++top] = elem;
}
else
throw new Exception("Stack is already Full");
}
public T pop() throws Exception {
if(isEmpty()) {
return stackElem[top--];
}
else
throw new Exception("Stack is Empty");
}
public boolean isEmpty() {return top == -1;}
public boolean isFull() {return top==MAXSTACKSIZE-1;}
}
Postfix.class(Class having method for creating tree)
public class PostFix {
private String expression = new String("A*B+C");
private char [] expElem = expression.toCharArray();
/*Error on below Statement*/
private TreeStack<TreeTemp> stack1 = new TreeStack<>(new TreeTemp());
public TreeTemp makeTree() throws Throwable {
try {
for(int i=0;i<expElem.length;i++) {
ExpNode eNode = new ExpNode();
eNode.setiData(expElem[i]);
TreeTemp t = new TreeTemp();
t.setRoot(eNode);
if(!Character.isLetter(expElem[i])) {
t.setLeftTree(stack1.pop());
t.setRightTree(stack1.pop());
}
stack1.push(t);
}
return stack1.pop();
}catch (Exception e) {
throw new Exception("Stack Error while creating a Tree", e);
}
}
public static void main(String[] args) throws Throwable {
PostFix pf = new PostFix();
TreeTemp t = pf.makeTree();
}
Tree Class(Type which i want to add into Stack):
public class TreeTemp {
private ExpNode root;
private TreeTemp leftTree;
private TreeTemp rightTree;
/*public TreeTemp(ExpNode expNode) {
root = expNode;
}*/
public TreeTemp getLeftTree() {
return leftTree;
}
public void setLeftTree(TreeTemp leftTree) {
this.leftTree = leftTree;
}
public TreeTemp getRightTree() {
return rightTree;
}
public void setRightTree(TreeTemp rightTree) {
this.rightTree = rightTree;
}
public ExpNode getRoot() {
return root;
}
public void setRoot(ExpNode node) {
this.root = node;
}
}
Can someone pls give some pointers.
Your TreeStack has only one constructor. Here it is:
public TreeStack(Class<T> t) {
Thus, to invoke it, you need to pass the class object that represents the class associated with the T type. So, the class itself, not 'some particular instance of T'. When you call it on your error line:
private TreeStack<TreeTemp> stack1 = new TreeStack<>(new TreeTemp());
You are passing an instance of TreeTemp. Not the concept 'TreeTemp, the class'. Try new TreeStack<>(TreeTemp.class);
Note that as a general rule, passing a Class<T> is a code smell; you're trying to make generics something that it isn't (you're trying to runtime reify). This is objectively bad: It means you can't make a TreeStack<List<String>>, for example, because you're restricted to the overlap where both generics as well as j.l.Class instances can represent the thing, and that's just simple, non-genericsed, non-primitive classes.
final T[] stackElem = (T[]) Array.newInstance(t, MAXSTACKSIZE);
Looks like the only reason you want that class is to make sure your array is properly typed.
This is not neccessary. Just make a new Object[] array, and cast to T anytime you need to return a T. Now your TreeStack constructor needs no arguments at all.
Check the source of java.util.ArrayList, which agrees with this assessment; it is backed by an Object array, not a T[].
The TreeStack constructor accepts a Class<T>, not a T, so you should do:
new TreeStack<>(TreeTemp.class);
Since this is an exercise to create expression trees, you don't really need to implement stacks from scratch. You should just use the ArrayDeque class through the Deque interface in the Java Collections API.
private Deque<TreeTemp> stack1 = new ArrayDeque<>();
Deque has all the methods your TreeStack has, and many more.

extending java.lang.String in groovy script

i've a rather complex problem. I'am currently developing a a little groovy based script language for an ERP System. The functions and syntax of "my" script language are based on the already existing old FO language which is used by the erp system.
Therefore: I'am getting values from the ERP with calls like h.fieldname, where h the currently selected dataset is and fieldname the name of the field I want my field value from.
I get the field value e.g. of type String. What I now want is to extend these strings I retrieve with a few functions, which are based on the "old" syntax.
// some samples
// get last 3 characters
h.fieldname >> 3
// get first 4 characters
h.fieldname << 4
// should still work even if h.fieldname, returns something which extends String but is not a String
assert h.fieldname == "Foo"
UPDATE
I tried to make use of the answer of #daggett, here my approach:
public abstract class BaseScript extends Script implements GroovyObject {
#Override
public Object run() {
Object o = null;
try {
final ExpandoMetaClass metaClass = new ExpandoMetaClass(String.class, false, true);
//Closure c = { int x-> delegate[-x..-1] };
//ClosureMetaMethod foo = new ClosureMetaMethod​("rightShift ", c , doCall);
metaClass.initialize();
o = runCode();
} catch (Exception e) {
this.onerror(e);
} finally {
this.always();
}
return o;
}
public abstract Object runCode();
public Object always() {
return null;
}
public Object onerror(Object ex) {
if (ex instanceof Exception) {
Exception e = (Exception) ex;
e.printStackTrace();
}
return null;
}
}
But honestly i've no idea how to implement it and I also can't find any example.
UPDATE 2 and solution
Based on the answer of #daggett.
package groovy.runtime.metaclass.java.lang;
import groovy.lang.DelegatingMetaClass;
import groovy.lang.MetaClass;
public class StringMetaClass extends DelegatingMetaClass {
public StringMetaClass(Class<?> theClass) {
super(theClass);
}
public StringMetaClass(MetaClass metaClass) {
super(metaClass);
}
#Override
public Object invokeMethod(Object object, String name, Object[] args) {
// implementiert "test" >> 3
if (name.equals("rightShift")) {
if (args.length == 1) {
if (args[0] instanceof Integer) {
String str = object.toString();
int x = ((Integer) args[0]).intValue();
if (str.length() > x) {
return str.substring(str.length() - x);
}
return str;
} else {
throw new IllegalArgumentException("wrong argument type, should be integer");
}
} else {
throw new IllegalArgumentException("too many arguments");
}
}
// implementiert "test" << 3
if (name.equals("leftShift")) {
if (args.length == 1) {
if (args[0] instanceof Integer) {
String str = object.toString();
int x = ((Integer) args[0]).intValue();
if (str.length() > x) {
return str.substring(0,x);
}
return str;
} else {
throw new IllegalArgumentException("wrong argument type, should be integer");
}
} else {
throw new IllegalArgumentException("too many arguments");
}
}
else {
return super.invokeMethod(object, name, args);
}
}
}
you can't extend string class because it's final, however in groovy you can add new methods to string class with help of metaclass
String.metaClass.rightShift = { int x-> delegate[-x..-1] }
"1234567890" >> 3
returns
890
in the same way implement the method leftShift for <<
the last request (assert s1==s2) is not relevant because String is a final class (not extendable)

incompatible return type using multiple classes

Im writing a program to simulate simple queues of Process Control Blocks and having an issue with a return value in my returnPcb() method. I am getting an "invalid return type". I know the return type in my method is a Pcb, but I cannot change it. I want to return the value of -1 if the the call to removePcb() is false. My thought was to create a new Pcb, set a value to -1, and return that value. This is where I am running into issues. I need help returning -1 when the condition is false. Thank you.
MasterQueue Class:
import java.util.*;
public class MasterQueue {
HashMap<String,Queue<Pcb>>hash;
MasterQueue(){
hash = new HashMap<>();
}
public boolean addQueue(String nameIn){
String QueueName = nameIn;
if(hash.containsKey(QueueName)){
return false;
}
//else add new queue the hashmap
else{
Queue<Pcb> q = new LinkedList<>();
hash.put(QueueName,q);
return true;
}
}
public boolean addPcb(Pcb p,String nameIn){
String PcbName = nameIn;
//if queue exist in the list then add the pcb to it
if(hash.containsKey(PcbName)){
hash.get(PcbName).add(p);
return true;
}
//else return false
else{
return false;
}
}
public Pcb removePcb(String nameIn){
String RemovePcbName = nameIn;
//if this queue exist in the list then remove first element from the queue
if(hash.containsKey(RemovePcbName)){
return hash.get(RemovePcbName).remove();
}
Pcb p = new Pcb(0, 0, 0, -1);
return p.getPid();
}
}
PCB Class:
public class Pcb {
private int low;
private int high;
private int state;
int pid;
Pcb(int lowMemIn, int highMemIn, int stateIn, int pidIn){
setLowMem(lowMemIn);
setHighMem(highMemIn);
setState(stateIn);
setPid(pidIn);
}
public void setLowMem(int lowMemIn){
low = lowMemIn;
}
public int getLowMem(){
return low;
}
public void setHighMem(int highMemIn) {
high = highMemIn;
}
public int getHighMem(){
return high;
}
public void setState(int stateIn){
state = stateIn;
}
public int getState() {
return state;
}
public void setPid(int pidIn){
pid = pidIn;
}
public int getPid(){
return pid;
}
}
Test
#Test
public void testAddPcb1() {
Pcb pid1 = new Pcb(1, 2, 3, 4);
MasterQueue mq1 = new MasterQueue();
mq1.addQueue("miniQueueStr");
Assert.assertTrue("error", mq1.addPcb(pid1, "miniQueueStr"));
Your method is currently defined as:
public Pcb removePcb(String nameIn){
String RemovePcbName = nameIn;
//if this queue exist in the list then remove first element from the queue
if(hash.containsKey(RemovePcbName)){
return hash.get(RemovePcbName).remove();
}
Pcb p = new Pcb(0, 0, 0, -1);
return p.getPid();
}
so you promised the compiler that this code would be returning a Pcb object, and nothing else. You can't just decide to make it return something else instead, it has to be a Pcb object.
So do that: you define that failcase Pcb p = Pcb(0,0,0,-1) so just return that p at the end of the function and the compiler will be happy.
However, if there is no matching Pcb, you really shouldn't be returning a Pcb object that happens to be set to values that you assume have meaning without formally declaring it as some constant, at which point things get silly... What you probably want to do instead is make your function throw:
public Pcb removePcb(String nameIn) throws NoSuchElementException {
String RemovePcbName = nameIn;
//if this queue exist in the list then remove first element from the queue
if(hash.containsKey(RemovePcbName)){
return hash.get(RemovePcbName).remove();
}
throw new NoSuchElementException();
}
And then in your consuming code, put that removal call inside a try/catch and do what you as programmer know needs to happen when someone tries to remove a Pcb that doesn't exist.

java.lang.Field equivalent in c++

I have a code that uses Field built in function in java and i could not find a way to replace it in c++ the code is shown below,
import java.lang.reflect.Field;
public class ParameterValue {
public String objectPath;
public Object objectReference;
public String fieldPath;
public String fieldPathNoCase;
public Field field;
public double value;
public ParameterValue(String path, ObjectTree tree, Field fieldInfo) {
objectPath = path;
objectReference = tree.getObject(path);
field = fieldInfo;
fieldPath = objectPath + "." + field.getName();
fieldPathNoCase = fieldPath.toLowerCase();
read();
}
public int getPrecision() {
if (field.getType().getName() == "float" || field.getType().getName() == "double")
return 2;
else
return 0;
}
public double getPrecisionMultiplier() {
return Math.pow(10, getPrecision());
}
public void read() {
String type = field.getType().getName();
try {
if (type.equals("double"))
value = field.getDouble(objectReference);
else if (type.equals("float"))
value = field.getFloat(objectReference);
else if (type.equals("int"))
value = field.getInt(objectReference);
else if (type.equals("byte"))
value = field.getByte(objectReference);
else
throw new RuntimeException();
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
value = Math.round(value * getPrecisionMultiplier()) / getPrecisionMultiplier();
}
public void write() {
String type = field.getType().getName();
try {
if (type.equals("double"))
field.setDouble(objectReference, value);
else if (type.equals("float"))
field.setFloat(objectReference, (float)value);
else if (type.equals("int"))
field.setInt(objectReference, (int)Math.round(value));
else if (type.equals("byte"))
field.setByte(objectReference, (byte)Math.round(value));
else
throw new RuntimeException();
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public void rebind(ObjectTree tree) {
objectReference = tree.getObject(objectPath);
}
}
What i have understood from the code is that i need to find a class that can convert the value in it to Double, Float,etc. I have looked for something that can do this but i was not able to do so.
reference of the code:
https://www.programcreek.com/java-api-examples/index.php?source_dir=SecugenPlugin-master/src/sourceafis/simple/Fingerprint.java#
As per my knowledge there is no equivalent class in C++. Now for your requirement first you list out what are all a java.lang.reflect.Field class provides in java. Once you listed all the utility methods, just sort list all methods that you really requires in your C++ application. Once done you do create a C++ class with the same name and methods types and implement the logic by yourself if possible.

Categories