2017-03-09 68 views
1

我需要一個程序來隨機生成一個數字,然後將這個數字的x放在自己的行上,直到它輸出一行16個x,然後停止。到目前爲止,我的程序生成一個數字,但從不停止輸出我確定這是我的錯誤,但不知道需要改變的是什麼。這是我的代碼在這一刻。X的隨機生成數量

import java.util.Random; 

public static void main(String[] args) 
{ 
    toBinary(); 
    randomX(); 
} 

public static void randomX() 
{ 
    Random num = new Random(); 
    int ran = num.nextInt(16+1); 
    int xs = ran; 

    while(xs <= 16) 
    { 
     System.out.print("x"); 
    } 
} 
+0

請閱讀[我的解決方案](http://stackoverflow.com/questions/40185629/how-to-generate-random-passwords-with-options-in-java/40185656#40185656)到您的問題。順便說一句,它可以產生任何長度的任何字符序列,並且非常易於使用。 – DimaSan

回答

2

要解決這個問題,請考慮一下您可能需要的循環。
你需要打印x一定次數,這是一個循環。我還介紹了一個變量來跟蹤這個打印。
你需要繼續打印,直到你達到16點。這是另一個循環。

public static void randomX(){ 
    Random num = new Random(); 
    int xs = 0; 
    //This loop keeps going until you reach 16 
    while(xs <= 16){ 
    xs = num.nextInt(16+1); 
    int x = 0; 
    //This loop keeps going until you've printed enough x's 
    while (x < xs) 
    { 
     System.out.print("x"); 
     x++; 
    } 

    System.out.println("") 
    } 
} 
+1

儘管此代碼片段可能會解決問題,但[包括解釋](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)確實有助於提高帖子的質量。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。 – DimaSan

+1

@DimaSan增加了一些解釋。並添加了我忘記的換行符。 –

+0

@ Jean-Bernard Pellerin好吧,我將代碼重新格式化爲這樣,甚至將其複製以查看它是否可行,但編譯之後代碼沒有輸出。 – DPabst

1

您可以使用輔助計數器來管理循環並將其增加以退出循環。

int i = 0; 
while (i<xs){ 
    System.out.print("x"); 
    i++; 
} 

您可以查看更多關於Java循環這裏:

Tutorial about java while

2

你的版本有一些小的問題。這是一組建議修訂。

// create your random object outside the method, otherwise 
// you're instantiating a new one each time. In the long run 
// this can cause awkward behaviors due to initialization. 
public static Random num = new Random(); 

public static void randomX(){ 
    int ran; 
    do { 
     ran = 1 + num.nextInt(16); // move the +1 outside unless you actually want 0's 
     int counter = 0; 
     while(counter++ < ran) { 
     System.out.print("x"); 
     } 
     System.out.println(); // add a newline after printing the x's in a row 
    } while(ran < 16); 
} 

最大的問題是,你需要循環,外一個用於生成新的號碼和內部一個打印X的當前數量。

次要問題是,你的循環被檢查號碼< = 16.所有的值都< = 16,所以這是一個無限循環。

在評論中發現的其他建議。