senpaimaster senpaimaster - 1 month ago 8
Java Question

How to put different text in a message that is being printed from a loop

I am very new to Java and as such I am not too familiar with much of the lingo. I am sure someone has asked this before but I can't seem to figure out what phrase to search.

Anyways, my problem is that I am currently working on an assignment where I generate 5 random numbers, display them, add them up, and see if the number is prime. While I don't know how to do much of that, my problem is actually with displaying the randomly generated numbers. I'm not sure how to put code in here so I'll just copy and paste mine.

public static void main(String[] args) {
int sim = 0;
System.out.print("The five random numbers are: ");
for (int i = 0; i < 5; i++)
{
sim += (int)(Math.random()*2.9999) + 1;
System.out.print(sim + ", ");
}
}


Now my issue is, I'm trying to get it to display results like "The five random numbers are: 3, 6, 7, 10, and 12."

But instead I'm getting "The five random numbers are: 3, 6, 7, 10, 12," So how would I put the and and such into it while it's being generated by a loop? Would I need to have a separate loop or something? Sorry if this question is dumb, I'm just very lost on this project altogether.

Answer

This is a community wiki answer with @DevilsHnd's solution:

int sim = 0;
int nb=4;

System.out.print("The five random numbers are: ");
for (int i = 0; i <= nb; i++)
{
    sim += (int)(Math.random()*2.9999) + 1;

    if ( i < nb ) {
        System.out.print(sim + ", ");
    } else {
        System.out.print("and " + sim + ".");
    }
}

I get the feeling that sim += is an error.

If you wish to print the random number AND add them together, you may need an additional variable:

int sumSum=0;
int nb=4;

System.out.print("The five random numbers are: ");
for (int i = 0; i <= nb; i++)
{
    int sim = (int)(Math.random()*2.9999) + 1;
    sumSum += sim;

    if ( i < nb ) {
        System.out.print(sim + ", ");
    } else {
        System.out.print("and " + sim + ".");
    }
}

I added:

  • int sumSum=0;
  • sumSum += sim;

sumSum is not being printed, but holds the sum of the 5 numbers.

Comments