2016-06-21 332 views
-1

我有一個簡單的Java代碼,需要將程序循環回到給定輸入的開始位置。我不能發佈整個代碼,因爲它是用於分配的,但基本上我有一個用戶輸入,計算和打印結果部分,最後給出了以前輸入的所有結果,現在我需要重新啓動它。我已經使用do-while循環試過了,是這樣的:如何在Java中重新啓動/循環程序?

do 
    { 
    System.out.println("Enter Another Student? Y or N"); 
    sLoop = console.nextLine(); 
    }while (sLoop.equals("Y") || sLoop.equals("y")); 

但是,這只是顯示文本和結束程序,而不使用戶輸入值的選項。但是,我知道這是錯誤的,因爲它沒有給出任何跡象表明它應該回到頂端。任何幫助表示讚賞。我會公佈開始,所以你知道這看起來如何,但我不能發佈整個事情。

import java.util.*; 

public class ---- { 

    public static void main (String[] args) { 

    Scanner console = new Scanner (System.in); 

在此之後我有用戶輸入,這一切工作正常,但我在困惑如何從開始到結束循環程序。我想我可能不得不把我的整個代碼(在掃描儀控制檯下)做,然後放在最後,但我認爲'while'的條件不會起作用。我希望這是有道理的。謝謝!

此外,代碼單獨工作。但是當我開始輸入數據時,它停止工作,不允許用戶輸入。

+2

做',而(sLoop.equals( 「Y」)|| sLoop.equals( 「Y」));'必須',而(sRestart.equals( 「Y」 )|| sRestart.equals(「y」));'? –

+0

[適用於我。](https://ideone.com/EE9m8L)在我的測試中,我有沒有做過你沒做過的事情? – 4castle

+0

對不起,sLoop和sRestart是同一件事,我的意思是改變他們。它們是同一個變量。 – KenwayCreed

回答

0

如果你要循環的時間像10倍左右幕量:

int x = 0; 
while(x < 10){ 
    //Code here 
    x++; 
} 

如果您需要循環它對整個時間:

boolean running = false; 

這就是全球布爾

//When the program starts(Probably in constructor or main method) 
running = true; 

和循環:

while(running){ 
    //Code you want to loop here 
} 
+2

'如果你想循環10次左右的窗簾時間'你可能想要在那裏使用for循環 –

+0

但是沒有一定的時間我想重新啓動。該任務是創建一個代碼,允許教師輸入學生信息,如姓名和成績,然後詢問他們是否想要輸入另一名學生。如果是,請從頂部啓動該程序。如果沒有,請停止該程序 – KenwayCreed

+0

@ DonatPants我同意。我是一個noob然後 for(int x; x <10; x ++){//代碼在這裏}我從來沒有真正學過循環,所以我不知道這是否正確 –

0

你的第一個代碼示例幾乎是你所需要的。看看這個運行例如:

import java.util.Scanner; 

public class LoopStudents { 

    public static void main(String[] args) { 

     Scanner console = new Scanner(System.in); 

     String sLoop; 
     do { 
      // do something with the student 
      System.out.println("Enter name of student:"); 
      String name = console.nextLine(); 
      System.out.println("Name = " + name); 

      System.out.println("Enter Another Student? Y or N"); 
      sLoop = console.nextLine(); 
     } while (sLoop.equals("Y") || sLoop.equals("y")); 
    } 
}