Reputation: 85
I'm trying to create a program that takes 12 ints between 0 and 100, and puts them into an array.. then then two arrays multiply and the resulting 6 ints should go into a final array. But when I try to execute I'm able to enter the ints but nothing happens, I've a sneaky suspicion im stuck in a loop somewhere. Any advice would be appreciated.
note
I haven't included the calculations for the 2nd array as that's not where the problem is.. I can't even get to the 2nd array as its getting stuck somewhere
import java.util.*;
public class Calc {
static int[] level = { 60, 40, 20, 30, 40, 70 };
public static void workOut()
{
// after accepting an array of 12 ints should compute array of 6
// array declaration
int[] nums = new int[12];
Scanner sc = new Scanner(System.in);
System.out.println("Enter int 1 then int 1a,");
System.out.print("then int 2 then int 2a etc, until int 6 and 6a");
if (!sc.hasNextInt())
{
System.out.println("Must be Int!");
}
else
{
while (sc.hasNextInt())
{
for (int i = 0; i < 12; i++)
{
if (sc.nextInt() >= 0 && sc.nextInt() <= 100)
{
nums[i] = sc.nextInt();
}
else
{
System.out.print("Number between 0 and 100 please");
}
}
}
}
}
}
Upvotes: 1
Views: 2332
Reputation: 6230
When you do this:
if (sc.nextInt() >= 0 && sc.nextInt() <= 100)
{
nums[i] = sc.nextInt();
}
you're throwing away 2 input values for every 3 read. Doesn't look right, does it? You probably want to store the input and then compare:
int value = sc.nextInt();
if (value >= 0 && value <= 100)
{
nums[i] = value;
}
You may also want to check for valid input as well.
for (int i = 0; i < 12; i++)
{
int value;
do {
value = sc.nextInt();
} while (value < 0 || value > 100);
nums[i] = value;
}
Upvotes: 3
Reputation: 3763
You are reading integers in a completely wrong manner.
If you want to read 12 integer, for loop should be the first loop then you should control the input integer if it is valid.
for (int i = 0; i < 12; i++)
{
int value = sc.nextInt();
while(value < 0 || value > 100)
{
value = sc.nextInt();
}
nums[i] = value;
}
Upvotes: 1
Reputation: 3543
Instead of doing
if (sc.nextInt() >= 0 && sc.nextInt() <= 100) {
nums[i] = sc.nextInt();
}
Assign sc.nextInt()
to some value before. Because what you are doing now is unnecessary retrieving nextInt()
and losing its value.
Change your code right in the beginning of your while
loop like this:
while (sc.hasNextInt()) {
int myInt = sc.nextInt();
// ... rest of the code
Upvotes: 0