2016-11-11 45 views
-3

中定义我试图编写一个程序: 1)要求用户输入创建一个10个元素的数组 2)检查以确保元素是不同的 3)确定元素中的最高值。收到一个错误:变量我已经在方法主

我认为Im接近,但我不断收到此错误消息:

错误:变量i在方法主要已经定义(字符串[]) 对(INT I = 0;我< myList.length;我+ + ){

这里是我的全码:

import java.util.Scanner; 

public class max101 { 
public static void main(String[] args) { 

    double[] myList = new double[10]; 
    double max = myList[0]; 

    java.util.Scanner input = new java.util.Scanner(System.in); 
    System.out.print("Enter " + myList.length + " distinct numbers: "); 
    for (int i = 0; i < myList.length; i++) 
     myList[i] = input.nextDouble(); 

    for(int i = 0; i <myList.length; i++) { 

     for(int j = i+1; j<myList.length; j++) { 

      if(myList[i] == (myList[j])); { 
       System.out.println("Numbers are not distinct. Please try again and enter 10 distinct numbers"); 
      } 

      if(myList[i] != (myList[j])); { 
       for (int i = 0; i < myList.length; i++) { 
        if (myList[i] > max) max = myList[i]; 
        System.out.println("The maximum value is " + max); 
        } 
       }   
      } 
     } 
     } 
    } 
+4

您认为错误信息是什么意思? –

+0

我会收集,这意味着我不需要继续在for循环中定义int我 – user7147678

回答

0
  1. 尝试在你的循环使用不同的变量名
  2. 如果你不想做上述不重新初始化与int变量只是把i = 0

它也可能是考虑范围内的工作方式很有用。

0

我的怀疑是你没有正确地结束你的块 - 一个块的含义从{}。当我有我的IDE缩进你的代码,它是:

for (int i = 0; i < myList.length; i++) 
     myList[i] = input.nextDouble(); 

    for (int i = 0; i < myList.length; i++) { 

     for (int j = i + 1; j < myList.length; j++) { 

      if (myList[i] == (myList[j])) 
       ; 
      { 
       System.out.println("Numbers are not distinct. Please try again and enter 10 distinct numbers"); 
      } 

      if (myList[i] != (myList[j])) 
       ; 
      { 
       for (int i = 0; i < myList.length; i++) { 
        if (myList[i] > max) 
         max = myList[i]; 

        System.out.println("The maximum value is " + max); 

       } 
      } 
     } 
    } 

我想你现在看到i在里面一个for循环,已经声明了i声明。同样,一旦你检测到重复,我认为你应该跳出两个循环,而不是检查更多的重复,并且在用户输入10个新数字之前找不到最大值。

还有一个小费,不要在你的if ( ...... )之后加分号,它会打乱你的逻辑。

相关问题