简体   繁体   中英

Resetting array back to array[0] in a while loop java

I am trying to get my while loop always reset to array[0]. I am trying to make it so that I can say what my favorite class is, and if need be change my mind after I have chosen the first one. Currently the code only lets me output array[0] then [1] then [2] or [2] > [3] or [1] > [3] but not [2] > [1] or [3] > [1]. Thanks. I am using Java. edit** If it wasn't clear I am talking about the second while loop.

import java.util.*;

public class Hobby1 {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);

        int numClass;
        int a;
        int b;
        String j;
        System.out.println("How many classes");
        numClass = scan.nextInt();
        j = scan.nextLine();
        String[] Class = new String[numClass];
        a = 0;
        while (a < numClass) {
            System.out.println("What is class " + a + "?");
            Class[a] = scan.nextLine();
            a++;
        }
        System.out.println("Which class is most important");
        String input = scan.nextLine();
        b = 0;
        boolean be = true;

        while (be == true) {


            if (input.contains(Class[b])) {
                System.out.println("The class " + Class[b] + " is most important");
                input = scan.nextLine();
             }

            b++;
        }
    }
}

You have few problems here:

  • while (be == true) - you can just use while (be) // be is boolean
  • you never put be = false; , so you will have an infinite loop
  • how you iterate the array Class to compare to each value of it? you just check once in increment order b , you need to loop all array not only the current element on b

Ex:

for(String currentClass: Class){
   if (currentClass.equals(input)) {
       System.out.println("The class " + currentClass + " is most important");
   }
}

Check this and try to fix your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM