Skip to content
Advertisement

Save to a variable the number of times the user answered “no” in java

good afternoon, I’m studying java, happened to get an assignment to make the following questions:

  1. give input to the scanner “do you want to close this application? “
  2. If the answer is “no”, the input will appear again with the same question.
  3. If the answer is “yes” the input does not appear again.
  4. Save to a variable the number of times the user answered “no”

I want to make a count when the user answers NO it will count.

import java.util.Scanner;

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

        String inputClose = "TIDAK";
        int jumlah = 0;
        while (inputClose.equals("TIDAK")) {
            System.out.println("Apakah anda ingin menutup aplikasi ini ?");
            Scanner inputKeyboard = new Scanner(System.in);
            inputClose = inputKeyboard.nextLine().toUpperCase();
        }
        System.out.println("User yang menjawab TIDAK adalah : " + jumlah);
    }
}

Advertisement

Answer

Based on your question, you just need to save the result on ‘the number of times the user answered “no”‘. I suggest you to use while loop and a variable to store the value

...
     public static void main(String[] args) {
        String inputClose = "TIDAK";
        int jumlah = 0;
        while (inputClose.equals("TIDAK")) {
            System.out.println("Apakah anda ingin menutup aplikasi ini ?");
            Scanner inputKeyboard = new Scanner(System.in);
            inputClose = inputKeyboard.nextLine().toUpperCase();
            
            // add 'jumlah' value if input is still "TIDAK" after the scanner get the input value
            if (inputClose.equals("TIDAK")) jumlah++
        }

        System.out.println("User yang menjawab TIDAK adalah : " + jumlah);
    } 
...

but I suggest you to use more user friendly input detection if you getting the input from keyboard typing. Use the equalsIgnoreCase to able to take any other string "TIDAK" format. Here is the example

...
     public static void main(String[] args) {
        String inputClose = "TIDAK";
        int jumlah = 0;
        while (inputClose.equalsIgnoreCase("TIDAK")) {
            System.out.println("Apakah anda ingin menutup aplikasi ini ?");
            Scanner inputKeyboard = new Scanner(System.in);
            // no need to reformat to uppercase
            inputClose = inputKeyboard.nextLine();
            
            // add 'jumlah' value if input is still "TIDAK" after the scanner get the input value
            if (inputClose.equalsIgnoreCase("TIDAK")) jumlah++
        }

        System.out.println("User yang menjawab TIDAK adalah : " + jumlah);
    } 
...
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement