Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

292
Views
Java: cambia dentro del bucle do while

Traté de hacer varias selecciones aleatorias que imprimieran el mensaje para cada número de entrada, es decir, una serie de números (4 2 17 0) donde 0 detendría el código. Obtuve una salida incorrecta

 public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int number=scanner.nextInt(); int x = number; do{switch(x) { case 1: System.out.println("Language selection"); break; case 2: System.out.println("Customer support"); break; case 3: System.out.println("Check the balance"); break; case 4: System.out.println("Check loan balance"); break; case 0: System.out.println("Exit"); break; default: return; } if (x==0) {break;} x++; } while (true); } } ``` ![enter image description here](https://i.stack.imgur.com/RJBYn.jpg) ![enter image description here](https://i.stack.imgur.com/wCm4p.jpg)
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Puede usar Scanner#hasNextInt para terminar el bucle cuando se agotan los enteros.

Manifestación:

 import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNextInt()) { int x = scanner.nextInt(); switch (x) { case 1: System.out.println("Language selection"); break; case 2: System.out.println("Customer support"); break; case 3: System.out.println("Check the balance"); break; case 4: System.out.println("Check loan balance"); break; case 0: System.exit(0); } } } }

Una ejecución de muestra:

 4 2 17 0 Check loan balance Customer support

Además, tenga en cuenta que necesita un break para evitar que los casos se caigan sin darse cuenta. No vi ningún uso default en este caso y, por lo tanto, lo eliminé del código de demostración.

Alternativamente, usando un bucle do-while:

 import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int x = 0; do { x = scanner.nextInt(); switch (x) { case 1: System.out.println("Language selection"); break; case 2: System.out.println("Customer support"); break; case 3: System.out.println("Check the balance"); break; case 4: System.out.println("Check loan balance"); break; } } while (x != 0); } }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!