Read strings in java within a while or do-while loop

1

How do I read strings in java within a while or do-while loop? without error and does not read

Code:

package listas;

import static java.lang.System.exit;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Listas {
    //declaração de Variáveis
    static List lista = new ArrayList();
    static Scanner ler = new Scanner (System.in);

    public static void main(String[] args) {

        while (true) {            
            System.out.println("0-Sair");
            System.out.println("1-Cadastrar");
            System.out.println("2-Listar");
            System.out.println("3-Remover");
            char op = (char) ler.nextByte();
            switch (op) {
                case 0 : exit(0);break;
                case 1 : cadastrar(); break;
                case 2 : break;
                case 3 : break;
                default : {
                    System.out.println("Opção Inválida!");
                    break;
                }
            }
        }

    }

    public static void cadastrar () {
        System.out.print("Digite: ");
        String str = new String ();
        str = ler.nextLine();
    }
}
    
asked by anonymous 16.09.2017 / 09:53

2 answers

1

Try this:

package listas;

import java.util.Scanner;

public class Listas {

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

        while (true) {            
            System.out.println("0-Sair");
            System.out.println("1-Cadastrar");
            System.out.println("2-Listar");
            System.out.println("3-Remover");
            String op = ler.nextLine().trim();
            switch (op) {
                case "0":
                    return;
                case "1":
                    cadastrar();
                    break;
                case "2":
                    break;
                case "3":
                    break;
                default:
                    System.out.println("Opção Inválida!");
                    break;
            }
        }
    }

    public static void cadastrar() {
        System.out.print("Digite: ");
        String str = ler.nextLine();
    }
}

Remember that from Java 7, String s can be used in switch es.

Also, avoid using System.exit . This is a bad programming practice.

ler.nextByte() does not do what you expect. So use ler.nextLine() .

    
18.09.2017 / 23:38
0

Instead of

Scanner ler = new Scanner (System.in);

// ...

char op = (char) ler.nextByte();

you could use

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

// ...

String s = br.readLine();

.

More details and implementation options can be found at: Java: How to get input from System.console ()

    
16.09.2017 / 16:23