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

206
Views
Mientras que la declaración de error de impresión de bucle después de while (verdadero) está rota

En el siguiente código, estoy tratando de pedirle a un usuario que ingrese un número y, si es menor que 1, solicite otro número positivo.

Parece estar funcionando hasta que se ingresa el número positivo, pero el programa imprimirá un mensaje de error final después de que se proporcione el número positivo.

¿Cómo evito que se imprima este mensaje de error después de ingresar el número positivo?

 System.out.println("Enter number"); int x = 0; while (x < 1) { x = input.nextInt(); System.out.println("ERROR - number must be positive! Enter another"); }
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Puede agregar una declaración de break , que sale de un bucle, así:

 while (x < 1) { x = input.nextInt(); if (x >= 1) { System.out.println("Mmm, delicious positive numbers"); break; } System.out.println("ERROR - number must be positive! Enter another"); }

O alternativamente:

 while (x < 1) { x = input.nextInt(); if (x < 1) { System.out.println("ERROR - number must be positive! Enter another"); } else { System.out.println("Congratulations, you can read directions!"); } }
over 4 years ago · Santiago Trujillo Report

0

Lea el número inicial incondicionalmente antes del bucle. Luego, dentro del ciclo, mueva la impresión sobre la llamada nextInt() .

 System.out.println("Enter number"); int x = input.nextInt(); while (x < 1) { System.out.println("ERROR - number must be positive! Enter another"); x = input.nextInt(); }
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!