单独汇总不在数组中的随机数?

时间:2015-09-12 19:20:08

标签: java loops

这是我已经上交的学校作业的一部分,我被分成一部分,因为随机数的总和应该是将各个数字加在一起,而不是每一行。< / p>

所以如果这些行是:

1 2 3

4 5 6

总计应该是21,而不是我现在正在做的579。我一直在努力想要解决这个问题。我尝试为每个整数生成一个不同的随机数对象,总共三个,但这完全搞砸了我的输出。

我们下周要学习数组,在线研究之后,我可以使用数组轻松完成这项任务,但是分配是在没有数组的情况下完成的。如何单独汇总每个条目?谢谢你的帮助!

这是我的代码:

import java.util.Random;
import java.util.Scanner;

public class lottery {


public static void main(String[] args) {

Scanner input = new Scanner(System.in);
int gameType, gameTimes;
int randomNums, lotNum, sum = 0;    

System.out.println("\t\t Welcome to\n \t\tJAVA LOTTERY!\n\n\n");

System.out.print(" Would you like to play with 3, 4, or 5 numbers? ");
  gameType = input.nextInt();

System.out.println("\n\n Now think about a number with " + gameType + " digits and remember it!\n\n\n");

System.out.print(" How many games should we play? ");
  gameTimes = input.nextInt();  


System.out.println("\n\n We're all done! We played " + gameTimes + " games!\n\n" + 
        " The numbers randomly selected were: ");

for(int i = 0; i < gameTimes; i++)
  {
   lotNum = 0;

   for(int j = 0; j < gameType; j++)
   {
    randomNums = (new Random()).nextInt(10);

    lotNum = (lotNum * 10) + randomNums;

    System.out.print(" " + randomNums);    
   }//end nested for loop

   System.out.println();

   sum += lotNum;

  }//end for loop

System.out.println("\n\nThe total of all of the numbers was " + sum );  

input.close();
    }//end main method
}//end lottery class 

1 个答案:

答案 0 :(得分:3)

更改

lotNum = (lotNum * 10) + randomNums; 

lotNum += randomNums;