2016-11-08 20 views
0

)私はコンパイルするためにコードを取得しましたが、ユーザーの入力を受け取り、push()メソッドを使って文字列をスタックに追加します。次に、他の方法を使用して入力の順序を逆にします。たとえば、ユーザーがいくつかの文字列を入力します。 "Hello" "World" "!" そして、ユーザが入力として "end"と入力すると、プログラムはスタックへのプッシュを止め、逆の順序で印刷します: "!" 「世界」 「こんにちは」ここスタックを使用して逆順で文字列を出力するのを助ける必要があります(詳細は

は、以下の私のコードです:

public class stackReversal { 

    private Node first = null; 

    private class Node { 
     private String item; 
     private Node next; 
} 

    public boolean isEmpty() { 
     return (first == null); 
} 

    public void push(String s) { 
     Node node = new Node(); 
     node.item = s; 
     node.next = first; 
     first = node; 
} 

    public String pop() { 
     if (first == null) 
      throw new RuntimeException("Stack Empty!"); 
     String result = first.item; 
     first = first.next; 
     return result; 
} 

    public String popString() { 
     String result = ""; 
     Node current = first; 
     while (current != null) { 
      result += current.item; 
      current = current.next; 
} 
     return result; 
} 

    public String toString() { 
     StringBuilder nodes = new StringBuilder(); 
     Node node = first; 
     while (node != null) { 
      nodes.append(node.item); 
      node = node.next; 
} 
     if (isEmpty()) { 
      return ""; 
     } else { 
      return nodes.toString().substring(0, nodes.toString().length() -  4); 
     } 
} 

    public static void main(String[] args) { 
     stackReversal s = new stackReversal(); 
     Scanner input = new Scanner(System.in); 
     System.out.print("Enter strings:"); 
     String in = input.nextLine(); 
     while (!in.equals("end-of-input")) { 
      s.push(in); 
      if (in.equals("end")) 
       break; 
     } 
     System.out.println("Strings:" + s); 
    } 
} 
+0

私たちがコンパイルとテストをするためのオーバーヘッド、コードとコードを書式化して行単位で表示するためのオーバーヘッドを追加してください。 –

+0

プラス:私たちがあなたを助けるために時間を費やしたい。したがって、ソースコードを適切に書式設定/インデントするのに数分を費やすのに十分なほど丁寧でなければなりません。あなたは知っています:可読性**事項**! – GhostCat

答えて

0

あなたのループは、単に動作しませんでした、あなたはそれに、任意の終了条件を持っていませんでした。

以下に、あなたのmainメソッドを変更し

public static void main(String[] args) 
{ 
    StackReversal s = new StackReversal(); 
    Scanner input = new Scanner(System.in); 
    System.out.print("Enter strings:"); 
    String in = ""; 
    while (!in.equals("end")) 
    { 
     in = input.nextLine(); 
     if (in.equals("end")) 
      break; 
     else 
      s.push(in); 
    } 
    System.out.println("Strings:" + s); 
} 
  1. 終了の文字列と終了を同じ条件でなければなりません。だからend
  2. input.nextLine();は、ループ内にあり、スタックにendを追加することを避けるためにelse文である必要がありinたび
  3. s.push(in);に割り当てられている必要があります。
+0

ありがとうございました –

関連する問題