[英]why is my stack.size() method not working?
import java.util.Scanner;
import java.util.*;
/**
* Write a description of class RPN here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class RPN
{
// instance variables - replace the example below with your own
private Stack stack;
private Menu menu;
/**
* Constructor for objects of class RPN
*/
public RPN()
{
// initialise instance variables
stack = new Stack();
menu = new Menu();
}
public boolean isInteger(String ytemp)
{
//for (int i = 0; i<ytemp.length; i++)
//{
try
{
Integer.parseInt(ytemp);
return true;
}
catch( Exception e )
{
return false;
}
}
/**
* An example of a method - replace this comment with your own
*
* @param y a sample parameter for a method
* @return the sum of x and y
*/
public String[] processString()
{
stack.initialiseStack();
String[] temp;
String delimiter = ",";
System.out.println("Please input a combination of integers and operators, separated by a comma but no spaces (e.g. 3,9,2,+,5,*,-)");
Scanner s = new Scanner(System.in);
String string = s.nextLine();
temp = string.split(delimiter);
return temp;
}
public void validateString(String[] xtemp)
{
for (int i = 0; i<xtemp.length; i++)
{
try
{
if(xtemp[i].equals("+"))
{
int a = stack.pop();
int b = stack.pop();
int c = b + a;
stack.push(c);
}
else if(xtemp[i].equals("-"))
{
int a = stack.pop();
int b = stack.pop();
int c = b - a;
stack.push(c);
}
else if(xtemp[i].equals("*"))
{
int a = stack.pop();
int b = stack.pop();
int c = b * a;
stack.push(c);
}
else if(xtemp[i].equals("/"))
{
int a = stack.pop();
int b = stack.pop();
int c = b / a;
stack.push(c);
}
else if(isInteger(xtemp[i]) == true)
{
int n = Integer.parseInt(xtemp[i]);
stack.push(n);
}
else
{
System.out.println("invalid input. Please ensure that your input solely consists of integers and the 4 main operators (+, -, *, /) separated by a comma. an example of a valid input would be the following: 4,7,+,2,*");
validateString(processString());
}
}
catch (EmptyStackException e)
{
System.out.println("Error identified: " + e.getErrorMessage());
}
}
if (stack.size() == 1)
{
stack.printStack();
}
}
}
如果最后的堆棧大小不是 1,我希望我的代碼給出錯誤。為什么它無法識別 stack.size 方法? 這不是 Java.util.* 的一部分嗎? 你認為這是因為我已經有一個堆棧 class 所以它與它混淆了嗎? 抱歉,如果這是一個奇怪的問題,但我真的需要幫助...................................... ..................................................... ..................................................... ..................................................... ..................................................... ..................................................... ..................................................... ..................................................... ..................................................... ..................................................
java.util.Stack
沒有size()
方法。 它有empty()
方法。
嘗試使用empty()
方法來解決您的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.