在另一个 for 循环中使用一个 for 循环中的 int。 JAVA

问题描述 投票:0回答:1

我需要能够使用一个 for 循环来填充数组,然后使用作为输入给出的最后一个 int 作为阈值。然后我尝试使用另一个 for 循环将数组中的值与阈值进行比较,如果它们小于该值,我会将它们输出。我的代码已接近完成,虽然它可能很笨重,但我一直在工作,直到我与数组进行比较,这表明我的 maxValue int 尚未初始化,即使它在第一个循环中被分配了一个值。请让我知道我哪里出错了,我迷路了。

导入java.util.Scanner;

public class LabProgram {
   public static void main(String[] args) {
      Scanner scnr = new Scanner(System.in);
      int[] userValues = new int[20];   // List of integers from input
      int numVals;
      int maxValue;
      int i;
  
      // The first input is to set the number of values that will be inputted. 
      numVals = scnr.nextInt(); 

      // The first for loop that sets the values for the array.
      for (i = 0; i < numVals; i++) { 
         userValues[i] = scnr.nextInt();
      }
 
      // The second for loop that sets the max value. Probably a better way to do this.
      for (i = numVals - 1; i > numVals - 2; i--) {
         maxValue = userValues[i];  
      }
  
      // This third for loop is where the error is coming from. 
      for (i = 0; i < numVals; i++) {
         if (userValues[i] <= maxValue) {
            System.out.print(userValues[i] + ",");
         }
      }
  
  
     
   }
}

这是我收到的错误消息: LabProgram.java:22:错误:变量 maxValue 可能尚未初始化 if (用户值[i] <= maxValue) {

java loops for-loop integer
1个回答
0
投票

所以我找到了一种方法来获得我所希望的结果,但现在我遇到了一个我不知道如何解决的问题。我不确定我是否可以用我的代码来修复它,或者这是否是实验室程序本身的问题。

import java.util.Scanner; 

public class LabProgram {
   public static void main(String[] args) {
      Scanner scnr = new Scanner(System.in);
      int[] userValues = new int[20];   // List of integers from 
input
      int numVals;
      int maxValue;
      int i;
  
  
      numVals = scnr.nextInt();
  
      for (i = 0; i < numVals; i++) {
         userValues[i] = scnr.nextInt();
      }
      for (i = numVals-1; i > numVals - 2; i--) {
          maxValue = userValues[i];
     
      }
      for (i = 0; i < numVals; i++) {
         if (i < numVals-1){
         if (userValues[i] <= userValues[numVals-1]) {
            System.out.print(userValues[i] + ",");
         }
         }
      }
      System.out.println("");
  
     
    }
 }

所以我可以通过最后两个测试,但第一个测试一直失败。

1:比较输出 0 / 3 输出不同。请参阅下面的亮点。

输入 5 50 60 140 200 75 100

你的输出 50,60,

预期产出 50,60,75,

2:比较输出 3 / 3 输入 5 50 60 140 200 75 70

你的输出 50,60,

3:比较输出 4 / 4 输入 7 25 32 27 28 27 25 31 30

你的输出 25,27,28,27,25,

第一个 int 输入应该定义后面有多少个 int。第一个测试说它将是 5,然后提供 6 个输入,这会导致我的代码失败。有什么办法可以解决这个问题还是我只是实验室的一时兴起?感谢您的意见!

© www.soinside.com 2019 - 2024. All rights reserved.