저는 여기 프로그래밍과 프로그래밍에 익숙합니다. 나는 강사가 충분한 질문이있을 때 도움이되지 않기 때문에 다른 주제들을 혼자서 공부하려고 노력하고있다. 제네릭 스택을 사용하여 역순으로 말하고 싶습니다.스택으로 단어 반전하기
pop, push, isEmpty 및 peek 메서드가 작동합니다. (필자가이 프로그램을 사용하기 전에 만든 간단한 프로그램으로 테스트했습니다.) 출력 결과는 char하지만 역순으로 표시됩니다. 나에게 각 char 앞에 null을 준다!
내 질문 : 왜 이런 일이 발생합니까? 그리고 용량이 9 인 경우 expandCapacity 메서드를 사용할 수 있지만 입력이 제한을 통과 할 때 적용되지 않습니다.
여기 여기 내 코드
package Stack;
import java.util.Scanner;
public class ReverseDriver<T> {
private static String out;
private static String in;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your sentence: ");
in = input.nextLine();
int size = in.length();
ArrayStack<Character> revStack = new ArrayStack<>(size);
for (int i = 0; i < in.length(); i++) {
char u = in.charAt(i);
revStack.Push(u);
if (in.length() > 9) {
revStack.expandCapacity();
}
}
while (!revStack.IsEmpty()) {
char u = revStack.Pop();
out = out + u;
System.out.flush();
System.out.print(out);
}
}
}
의 출력
run:
Enter a word:
word
nullr
nullro
nullrow
Exception in thread "main" java.lang.NullPointerException
at Stack.ReverseDriver.main(ReverseDriver.java:37)
Java Result: 1
BUILD SUCCESSFUL (total time: 2 seconds)
편집입니다 : 여기에 내가 작업하는 상기 방법이다. out
의
@Override
public void Push (T element)
{
if (count == stack.length){
expandCapacity();
}
stack[++count] = element;
//System.out.println(count);
}
@Override
public String toString()
{
String result = "<top of stack>\n";
for (int index=count-1; index >= 0; index--){
result += stack[index] + "\n";
}
return result + "<bottom of stack>";
}
@Override
public boolean IsEmpty()
{ //Checks if array is empty
if(count == 0){
System.out.println("Nothing");
}
return count == 0;
}
public T Pop()
{
T output;
output = (stack[count - 1]);
count--;
return(output);
}
@Override
public T Peek()
{
//looks at the object at the top of this stack without removing it
//from the stack.
if(stack.length == 0){
// {
System.out.println("Cant peek a ghost");
}
return(stack[--count]);
}
// else
// {
// System.out.println(stack[count-1]);
// }
// }
@Override
public int Size()
{
//Sets the size of this vector
if(stack.length == 0){
System.out.println("Nothing inside");
}
System.out.println("The array's size is : " + count);
return count;
}
}
내가 감사 드리며 당신이 단지 우리에게이 이유에 좀 더 통찰력을 제공하기 위해, 당신은 우리에게 expandCapacity 및 IsEmpty 함수 방법의 코드를 적어주세요 수 일하고 말했다 일어납니다 :) – christopher
출력을 생성하는 코드가 똑같은가요? "단어 입력"vs "문장 입력" –
메모 :'in.length()가 10이면'expandCapacity'가 10 번 호출됩니다. 의도적 인? 또한'in'과'out'은 statics가 아닌 main의 지역 변수가되어야합니다 (적어도 이것이 "진짜"프로그램이라면). – hyde