Confirmation code

Asked

Viewed 77 times

3

I wanted to make a scheme to confirm a question. If the answer was Yes to the question, an ok message would appear. If it was No or different from Yes, I would ask if the person would like to confirm again. I made this algorithm there, but it does not enter the loop.

package resposta;

import java.util.Scanner;


public class Resposta {


    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Confirma?");
        String resp = " ";
        String conf = sc.nextLine();
        while(resp.equals("s")){
            if(resp == "s"){
                System.out.println("confirmado");
            }else{
                String resp2 = "Confirme?";
                conf = sc.nextLine();
                conf = conf + 1;

            }
        }


        sc.close();

    }


    }
  • 1

    Why do you wear resp and conf as two variables and not just one?

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site

1 answer

8

The code is complicating what you don’t need:

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String resp = " ";
        while (!resp.equals("s")) {
            System.out.println("Confirma?");
            resp = sc.nextLine();
        }
        System.out.println("confirmado");
        sc.close();
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

No need to ask twice. No need to check again inside the loop what is already being checked in the loop condition. I’m accepting to enter initially anyway and it stays in the loop until the letter s is typed. When this happens the loop will close, it confirms and closes the application.

I simplified what was not being used and took what didn’t even make sense. I would simplify it a little more, but not everyone like that. I had reduced the amount of variables, now I do even more:

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (true) {
            System.out.println("Confirma?");
            if (sc.nextLine().equals("s")) break;
        }
        System.out.println("confirmado");
        sc.close();
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Thanks my friend, gave it right. Thank you very much.

  • @Adautoalmeida see in the [tour] the best way to say workmanship.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.