2017-03-09 57 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,所以这是一个无限循环。

在评论中发现的其他建议。