0

hey im a very rookie coder, and i was trying to create an average calculator program. However once I use this code, it skips my switch case and goes immediately to my default case. How can I fix this?

import java.util.*;

class AverageCalculator {
    public static void main(String[] args) {
        Scanner ramim = new Scanner(System.in);
        int totalToAverage;
        int counter = 1;
        int ans;
        String ans2;
        int tally = 0;

        System.out.print("How many different inputs do you want to put in?: ");
        totalToAverage = ramim.nextInt();
        System.out.println("Your input # is " + totalToAverage + ".");

        while (counter <= totalToAverage) {
            System.out.print("Enter number " + counter + ":");
            counter++;
            ans = ramim.nextInt();
            tally = ans + tally;
        }

        System.out.println("You have entered " + --counter + " numbers." + "Your total is " + tally + ".");

        System.out.println("Would you like to find your average?");
        ans2 = ramim.nextLine();

        switch (ans2) {
        case "yes":
            System.out.println("note: dont worry about this part yet");
            break;

        case "no":
            System.out.println("Alright.");
            break;

        default:
            System.out.println("Please enter yes or no only. :)");
            break;
        }
    }
}
Hovercraft Full Of Eels
  • 276,051
  • 23
  • 238
  • 346
xramim
  • 1
  • 1

1 Answers1

0

You need to use ramim.nextLine(); twice to get String input after getting int input. This is because ramim.nextInt(); does not read the last ENTER character you type. So do something like:

System.out.println("Would you like to find your average?");
ramim.nextLine();
ans2 = ramim.nextLine();
Raymo111
  • 387
  • 3
  • 21