2017-05-28 87 views
-1

好吧,這是我的代碼到目前爲止,我真的需要幫助,使其退出後,我輸入退出,也爲程序不鍵入一個字符串後結束。任何幫助或鏈接到一些幫助將不勝感激我是一個非常新手的程序員。如何讓我的程序在進入退出後退出

import java.util.Scanner; 
import java.io.*; 

public class reverse 
{ 
    public static void main(String [] args) 
    { 
     String input = null; 

     Scanner keyboard = new Scanner(System.in); 

     System.out.print("Please enter a string for reversal or type QUIT to exit: "); 

     input = keyboard.nextLine(); 
     if(input.equals("quit")) 
     { 
      //close the program 
     } 

     Reverser(input, (input.length() - 1)); 
     System.exit(0); 


    } 
    public static void Reverser(String str, int size) 
    { 
     if(size>=0) 
     { 
      System.out.print(str.charAt(size)); 
      Reverser(str,size-1); 
     } 
    } 




} 
+1

將'System.exit(0);'移至'if'條件。 –

+0

DANG,工作idk爲什麼我想離開它 – akay

+1

如果你希望你的程序能夠接受多個字符串,你最好學習循環:'for'循環,'while循環和'do .. .while'循環。閱讀關於他們[這裏](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html)和[here](http://docs.oracle.com/javase/tutorial/java/對於初學者來說,nutsandbolts/for.html)。 –

回答

0

你可以嘗試這樣的事情

input = keyboard.nextLine(); 
while(!input.equals("quit")) 
{ 
    Reverser(input, (input.length() - 1)); 
    System.out.println("Please enter a string for reversal or type QUIT to exit: "); 
    input = keyboard.nextLine(); 
} 
0

這裏是一個可能的解決方案,它輸入多個輸入之後並沒有結束:

Scanner keyboard = new Scanner(System.in); 

    String input; 
    System.out.println("Please enter a String for reversal or type quit to exit:"); 
    while (!(input = keyboard.nextLine()).equals("quit")) { // wait until the input is quit 
     // do stuff with input 
    } 

    keyboard.close(); // don't forget to close the scanner when you are done 

控制檯輸出:

Please enter a String for reversal or type quit to exit: 
blah 
test 
quit 

Process finished with exit code 0 

如果你完成了whi le循環,只需加上break;即可。