1

我正在尝试创建一个程序,它需要 0 到 100 之间的 12 个整数,并将它们放入一个数组中。然后两个数组相乘,得到的 6 个整数应该进入一个最终数组。但是当我尝试执行时,我可以输入整数但没有任何反应,我有一个偷偷摸摸的怀疑我被困在某个地方的循环中。任何意见,将不胜感激。

笔记

我没有包括第二个数组的计算,因为那不是问题所在。我什至无法进入第二个数组,因为它卡在某个地方

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");
                    }
                }
            }   
        }
    }
}
4

3 回答 3

3

当你这样做时:

if (sc.nextInt() >= 0 && sc.nextInt() <= 100)
{
    nums[i] = sc.nextInt();
}

您每读取 3 次就会丢弃 2 个输入值。看起来不太对,是吗?您可能想要存储输入然后比较:

int value = sc.nextInt();
if (value >= 0 && value <= 100)
{
    nums[i] = value;
}

您可能还想检查有效输入。

for (int i = 0; i < 12; i++)
{
    int value;
    do {
        value = sc.nextInt();
    } while (value < 0 || value > 100);
    nums[i] = value;
}
于 2013-11-04T16:31:04.763 回答
1

您正在以完全错误的方式读取整数。

如果你想读取 12 个整数,for 循环应该是第一个循环,那么你应该控制输入整数是否有效。

for (int i = 0; i < 12; i++)
{
   int value = sc.nextInt();
   while(value < 0 || value > 100)
   {
       value = sc.nextInt();
   }
   nums[i] = value;
}
于 2013-11-04T16:36:49.600 回答
0

而不是做

if (sc.nextInt() >= 0 && sc.nextInt() <= 100) {
    nums[i] = sc.nextInt();
}  

之前赋值sc.nextInt()给某个值。因为你现在正在做的事情是不必要的检索nextInt()和失去它的价值。

while在循环开始时更改代码,如下所示:

while (sc.hasNextInt()) {
    int myInt = sc.nextInt();
    // ... rest of the code
于 2013-11-04T16:32:52.987 回答