[英]Is there an equivalent method to java's `getDeclaredMethod()` to test private methods of classes in Typescript?
[英]private classes in method - java
我正在嘗試編寫一個程序,該程序以明顯的波蘭形式(即6,3,'*',7,2,')接受代數表達式(即(6 * 3)+(7-2))的輸入-','+'),方法是將整數放在堆棧上,並在前兩個元素上調用操作數,然后最后返回堆棧上的所有內容(希望堆棧上只有一個元素-答案)。
我是Java的新手,所以我確定這是一個非常平凡的問題,但是我似乎無法使正在使用的堆棧(名為“ store”)可以被其他方法訪問和編輯。類。
我的堆棧實現似乎工作正常,如果發生“火災”,我將其發布。
當函數必須調用操作數子函數之一(如add())時,就會出現我的問題。 似乎完全忘記了存儲存在並且已經被編輯,而是將其視為空堆棧。 我嘗試將“ this”扔到除了前兩個實例之外的所有事物的前面,但這並不過分。 如何獲得該功能以在其所有功能之間共享“存儲”?
樣品運行:
Eval myEval = new Eval;
myEval.evaluate(6, 3, '+', 4, 9, '*', '-');
Exception in thread "main" java.lang.NullPointerException
at Eval.add(Eval.java:45)
at Eval.evaluate(Eval.java:13)
public class Eval {
public stack store;
public Eval(){
stack store = new stack();
}
public int evaluate(Object ... parts){
for(Object part: parts){
if(part instanceof Character){
char operator = (Character) part;
if(operator=='+'){
add();
}
else if(operator=='-'){
subtract();
}
else if(operator=='*'){
multiply();
}
else if(operator=='/'){
divide();
}
else{
throw new IllegalArgumentException("Illegal operand");
}
}
else if(part instanceof Integer){
int number = (Integer)part;
store.push(part);
System.out.println(store.peek());
}
else{
throw new IllegalArgumentException("Expected char or int");
}
}
if(store.peek()==null){
throw new IndexOutOfBoundsException("No value to return");
}
return (int)store.pop();
}
private void add(){
int x=(int)store.pop(); //error occurs on this line
x+=(int)store.pop();
store.push(x);
}
private void subtract(){
int x=(int)store.pop();
int y=(int)store.pop();
x=y-x;
store.push(x);
}
private void multiply(){
int x=(int)store.pop();
int y=(int)store.pop();
x=y*x;
store.push(x);
}
private void divide(){
int x=(int)store.pop();
int y=(int)store.pop();
int z = Math.floorDiv(x,y);
store.push(z);
}
}
看起來您的構造函數Eval()將新堆棧分配給名為“ store”的臨時變量,該臨時變量不是Eval類的公共“ store”變量。 因此,輸入Add時,實例變量“ store”為null。 將Eval()的實現更改為:
public Eval(){
this.store = new stack();
}
否則,請為store(getStore)創建一個getter方法,並在該方法中將其實例化(如果為null),但是如果這樣做,則必須記住要通過getStore()而不是直接對其進行引用。
當堆棧為空時,您很有可能嘗試彈出。 同樣,當您已經知道堆棧將包含一個int時,也不必對x進行賦值轉換。 int x =(int)store.pop(); 可以只是int x = store.pop();
我建議向您的操作員功能添加檢查,例如:
if(stack.getLength() > 0) {
//then add operation
} else {
//throw an error
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.