I've just started learning Java, and I wanted to overcome a hurdle that showed up when trying to create a Java program for this 'problem'. This is the problem I had to create a program for:
Tandy loves giving out candies, but only has n candies. For the ith person she gives a candy to, she gives i candies to that person. For example, she first gives Randy 1 candy, then gives Pandy 2 candies, then Sandy 3. Given n, how many people can she give candies to?
Input Format
The first line is an integer x, denoting the number of test cases.
The next x lines will contain a single positive integer, n.
SAMPLE INPUT
2
1
5
Output Format
x lines, with each line containing a single integer denoting the number of people Tandy can give candies to.
SAMPLE OUTPUT
1
2
To solve this problem, I created a program, and it functions well, but it doesn't match what the problem is asking for. The code:
import java.util.Scanner;
public class PRB1CandyGame {
public static void main(String[] args)
{
Scanner cases = new Scanner(System.in);
int repeats = cases.nextInt();
while (repeats > 0)
{
int x = cases.nextInt();
int i = 1;
for(i = 1; x-i>=0; i++)
{
x = x-i;
}
System.out.println(i-1);
repeats--;
}
}
}
(Sorry if the code is messy!)
My code takes in the number of 'cases' and then that's how many times I can enter in a number of candies to get the number of people it can provide. However, my program takes the number of candies and then outputs the number of people right after, while I want it to take in all the inputs (number of inputs is based on what the user enters for the number of cases), and then output all the values, rather than what I have. If you can explain to me how I can do that, it will help a lot.
Thanks!