gpt4 book ai didi

java - 将 Java 堆栈与字符串元素结合使用

转载 作者:行者123 更新时间:2023-12-01 09:11:25 29 4
gpt4 key购买 nike

我正在尝试使用 java 堆栈将 String 值:名称插入其中,该值源自 Scanner 方法的输入。然后我想从堆栈中弹出名称,然后显示堆栈的逻辑和物理元素。我相信我应该使用数组堆栈,但不完全确定,因为我对堆栈没有太多的指导或经验。

目前,我在编译 Stack.java 文件时遇到以下错误。

Stack.java:24: cannot find symbol
symbol : method push(java.lang.String)
location: class java.lang.String[]
stack.push(s);

我几天来一直在研究这个问题并尝试不同的代码,但由于我对此非常陌生,并且我已经用尽了方法来操纵代码以使其工作。

我非常感谢一些建议...tnx!

这是我的堆栈类代码:

import java.lang.*;
import java.util.*;

public class Stack { //Create Class

private String stack[] ;
private int top;
private static final int SIZE = 5;
String name;
Scanner scan = new Scanner(System.in);

public Stack(int SIZE){
stack = new String [SIZE];
top = 0;
}

public void push(String s) { //Method to Insert

if (isStackFull())
System.out.println ("Stack is Full "); //If Stack full Print Full
else {
while (scan.hasNextLine()){
s = scan.nextLine();
stack.push(s);
}
stack[top] = s;
top++;
}
}

public String pop() { //Method to Delete

if (isStackEmpty())
System.out.println ("Stack is Empty "); //If Stack empty print Empty
else{
String value = stack[top];
top--;
return value;
}
return stack[top];
}

public String toString( ){ //Method print Logical Stack
if (isStackEmpty( ))
System.out.println ("Stack is Empty "); //If Stack empty print Empty
else
System.out.println("\nThe Stack");
String result = "";

for (int j=0; j < top; j++)

result = result + stack[j].toString() + "\n";

return result;
}

public boolean isStackEmpty() { //Method boolean type to check empty Stack
return (top == 0);
}

public boolean isStackFull() { //Method boolean type to check full Stack
return (top == (SIZE-1));
}
}

对于StackTest代码,一般我都会调用Stack中的方法。例如。

public class StackTest { //Create class
public static void main(String[] args){ //Main Method
Stack n = new Stack(); //Declare variables
Scanner in = new Scanner(System.in);
String response;
char x;

while(x != 'q' && x != 'Q'){        //While loop initiates if no q or Q char input

switch(x){ //Start of swtich for insert, delete, print physical, logical or default quite
case 'i':
n.push();
System.out.println ("Inserted item from Stack");
break;
case 'd':
n.pop();
System.out.println ("Deleted item from Stack");
break;
case 'p':
n.toString();
System.out.println ("Printed Physical Stack ");
break;

最佳答案

您的 push(String s) 方法正在对 String 调用 push() ,这是不正确的,而且 的逻辑Push(String s) 说起来很复杂,其实很简单,如下带注释的代码:

public void push(String s) {
if (isStackFull())
System.out.println ("Stack is Full "); //If Stack full Print Full
else {
stack[top] = s; //just add the string to the top of the stack
top++; //increment top
}
}

关于java - 将 Java 堆栈与字符串元素结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40900423/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com