SeanKin
SeanKin

Reputation: 3

how to output answer after each input using a loop?

If I wanted to enter 10 numbers, and after each number it displays the square root, how would I do this using a for loop?

int number; 
System.out.print("Enter a number: ");
num = input.nextInt();
for (count = 0; count <= 10; count++)
{
    System.out.println("The Square of Number is : "+(num*num));
    System.out.println("The Cube of Number is : "+(num*num*num));

I have tried this code. However, it displays 1 input 10 times. How do I get it to display after each input?

Upvotes: 0

Views: 310

Answers (3)

Redempt
Redempt

Reputation: 11

Move num = input.nextInt() inside the for loop, like @Pavneet Singh said. If you want it to display all 10 after they have been entered, use an int[] with a length of 10 like this:

int[] numbers = new int[10];

Upvotes: 1

eetschel
eetschel

Reputation: 46

If you want to output the square root after you entered a number, just put num = input.nextInt(); inside the for-loop, as already mentioned.

If you however want to input the 10 numbers first and then output the squares of every number, this would be a pretty good solution:

int[] numbers = new int[10];
for(int i = 0; i < numbers.length; i++) numbers[i] = input.nextInt();
for(int tempInt : numbers) System.out.println(Math.pow(tempInt, 2));

Upvotes: 1

a.deshpande012
a.deshpande012

Reputation: 744

Similar to what others have said, you are only getting input once, and then printing the output 10 times. input.nextInt() must be moved inside the for loop.

However, something that hasn't been said is that you aren't consuming the newline delimeter. (Assuming you're using the console, which it seems you are) When the user inputs text by hitting enter, there is a newline delimeter at the end of the input. You are only consuming the number, but not the newline.

An example of this can be found here.

Upvotes: 2

Related Questions