How to make the if-Else instruction work for reading integers

Asked

Viewed 301 times

0

My program compiled in cmd, but running does not execute the instruction if, showing only the last String and closes. I want the user to have the option to register another message. What possible solutions?

The program is as follows:

/*
 * Class do registo de mensagens
 */
import java.util.*;
public class RegistoDeMenssagem4 {
    public static void main(String[] args) {
        System.out.println("Bem vindo Utilizador"); // o número ou nome do utilizador 
        //Porque o registo de menssagem só é possível para números registados       
        System.out.println("Introduza o número da recarga");
        Scanner kb = new Scanner(System.in);
        int Recarga = kb.nextInt(); // exception para o nùmero

        // Aqui irei introduzir o try-catch exceptions para cada input                                  
        System.out.println("Têm mais recarga para registar?");
        System.out.println("responda `S´ para continuar ou `N´ para terminar");
        String resposta;
        resposta = kb.nextLine();

        if (resposta.equals("s")) {
            System.out.println("Introduza o número da recarga");
            Scanner kb2 = new Scanner(System.in);
            int MaisRecarga = kb.nextInt();
            System.out.println("Têm mais alguma recarga para registar?");
        } else {
            System.out.println("Obrigado, atê o próximo registo.");
            System.exit(0);

        }
    }
}
  • may be a case-by-case issue

  • Replace with if (resposta.equalsIgnoreCase("s")) if it makes no difference if it’s a capital S or a minuscule.

3 answers

9

The problem is that you are using the same number scanner in your answer. That way it will always fall into the else because you already have the value of the number you typed.

Create a new class object Scanner to read your answer:

 String resposta;
 Scanner kc = new Scanner(System.in);
 resposta = kc.nextLine();
  • 1

    Well noticed! I hadn’t even noticed it was the old scanner problem +1

  • rs, I took a little time to notice too. Silly mistakes are boring to find

  • They were negative but the answer solves the problem of the question, now if the form seems unorthodox, the problem is more of the class used for reading than of the answer itself.

1

"S" and "s" are different strings. equalsIgnoreCase() checks whether the String is equal, ignoring different uppercase/lowercase letters.

Example

System.out.println("S".equals("s")); //false  

System.out.println("S".equalsIgnoreCase("s"));//true  

I mean, you use equalsIgnoreCase() when you want to compare a String, without distinction between upper and lower case letters.

Details

  • I made the change to but the problem persists. Only executes the part of the code corresponding to the "Else" of the meter, even after the change.

  • @Diegoaugusto. Your solution worked. The program, after changing the name of the second scanner to: Scanner Kc = new Scanner(System.in); answer = Kc.nextLine();, ran as intended.

1


How about doing it this way?

import java.util.Scanner;

public class RegistoDeMensagem4 {

    private static int lerNumero(Scanner kb, String mensagem, String mensagemErro) {
        while (true) {
            System.out.println(mensagem);
            try {
                return Integer.parseInt(kb.nextLine());
            } catch (NumberFormatException e) {
                System.out.println(mensagemErro);
            }
        }
    }

    private static boolean lerSimNao(Scanner kb, String mensagem, String mensagemErro) {
        while (true) {
            System.out.println(mensagem);
            String x = kb.nextLine();
            if (x.equalsIgnoreCase("S")) return true;
            if (x.equalsIgnoreCase("N")) return false;
            System.out.println(mensagemErro);
        }
    }

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

        System.out.println("Bem-vindo, utilizador.");
        boolean maisRecarga = true;
        while (maisRecarga) {
            int recarga = lerNumero(kb, "Introduza o número da recarga: ", "Isso que você digitou não era um número. Por favor, tente novamente.");
            System.out.println("Você digitou " + recarga + ".");
            maisRecarga = lerSimNao(kb, "Tem mais recarga para registar?\nResponda `S´ para continuar ou `N´ para terminar: ", "Era para você responder S ou N! Por favor, tente novamente.");
        }
        System.out.println("Obrigado, até o próximo registro.");
    }
}

This program has the following:

  • The method lerNumero, which forces the typing of a number and insists until a number is entered.

  • The method lerSimNao, which forces the typing of S or N (uppercase or lowercase) and insists until one of the two is typed.

  • Uses only one Scanner.

  • Utilizes Integer.parseInt(kb.nextLine()) instead of kb.nextInt() to read numbers.

  • Allows the user to type as many entries as he wants.

  • Does not use System.exit(0) - Using this is generally a programming malpractice.

Here is an example of inputs/outputs:

Bem-vindo, utilizador.
Introduza o número da recarga: 1234
Você digitou 1234.
Tem mais recarga para registar?
Responda `S´ para continuar ou `N´ para terminar: S
Introduza o número da recarga: Banana
Isso que você digitou não era um número. Por favor, tente novamente.
Introduza o número da recarga: 4321
Você digitou 4321.
Tem mais recarga para registar?
Responda `S´ para continuar ou `N´ para terminar: J
Era para você responder S ou N! Por favor, tente novamente.
Tem mais recarga para registar?
Responda `S´ para continuar ou `N´ para terminar: n
Obrigado, até o próximo registro.

See here working on ideone.

  • I liked your suggestion. however, I am compiling in cmd and have the following error message:

  • class Registodemenssagem4 is public, should be declared in a file named Registodemenssagem4.java

  • I must say that I liked this suggestion and am about to adopt it.

  • I went to ideonee ví... but in cmd the error, whose message I described in the previous comment, bursts in line 3: public class Registodemenssagem4

  • Victor Stafuta worked! thanks. his version of the comic perfectly fulfills my idea.

  • @Well, I’m glad it worked out for you. These errors you have are because the class name should be the same as the file name if the class is public (but if it is not, it is not necessary). In ideone, the file he uses under the covers is called Main.java, and that is why I did not put the public in front of the class statement on ideone. Already here in the answer, I kept the public because this is how it will stay in your code on your computer.

Show 1 more comment

Browser other questions tagged

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