排序数组,重复局部变量,错误

时间:2015-03-07 13:24:55

标签: java drjava

我整天都在处理这段代码,而我似乎无法做到正确:(

import java.util.Random;
import java.util.Scanner;
import java.io.*;

public class TrialSixthree{
        public static void main(String[]args){
           Scanner i = new Scanner(System.in);

           int c;
           int choice;
           Random t = new Random();
            for (c = 1; c <= 5; c++) {
                System.out.println(t.nextInt(1000));
            }
            System.out.println(" \n1: BUBBLE SORT ");
            System.out.println(" 2: SELECTION SORT ");
            System.out.println(" 3: QUICK SORT ");
            System.out.println(" Choose a number from 1-3 ");
            choice= i.nextInt();

            if(choice == 1){
                System.out.print("You chose BUBBLE sort!");
                System.out.println(x[i]+"");//I don't know what's wrong in this line
                for(int i = 0 ; i < x.length-1 ; i++){
                  for (int j = 0 ; j < x.length-1 ; j++){
                    if ( x[j] > x[j]){
                        temp = x[j];
                        x[j] = x[j+1];
                        x[j+1] = temp;
                    }
                  }
                }
              } else if(choice == 2){
                  System.out.print("You chose SELECTION sort!");
                  System.out.println(x[i]+"");
                  int temp, min;
                  for(int i=0;i<x.length-1;i++) {
                      min = i;
                      for(int j=i+1;j<x.length;j++) {
                        if(x[min]>x[j]) {
                            min = j;
                        }
                        if(min!=i) {
                            temp = x[min];
                            x[min] = x[i];
                            x[i] = temp;
                        }
                      }
                    }
                  } else if(choice == 3){
                        System.out.println("You chose QUICK sort!");
                        System.out.println(x[i]+"");
                        int temp;
                        for(int i=0;i<x.length-1;i++) {
                            for(int j=i+1;j<x.length;j++) {
                              if(x[i]>x[j]) {
                                  temp = x[i];
                                  x[i] = x[j];
                                  x[j] = temp;
                              }
                            }
                        }
                    } else {
                          System.out.println("Not in the choices!");
                    }
                }
            }

我似乎无法做到这一点。我还是java的新手。出现重复的局部变量的错误。这是我的作业。请帮帮我:(

2 个答案:

答案 0 :(得分:1)

您宣布i两次:

Scanner i = new Scanner(System.in);

for(int i = 0 ; i < x.length-1 ; i++)

我建议你给Scanner变量一个更有意义的名字。

答案 1 :(得分:0)

您多次使用i变量 因此,重命名i变量

       Scanner i=new Scanner(System.in);

重命名i变量

       Scanner scan=new Scanner(System.in);