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

105
Views
Switch case that dosent continue in a while loop
  int selection;  
  selection = 0;

  
  while (selection != -1)
  {
     selection = menu();

     switch (selection)
     {
     case 1:
        System.out.println("Hur många varor vill du lägga till?");
        int numberOfArticles = input();
        System.out.print("Du har lagt till:  " + numberOfArticles + " varor\n");
        articles = checkFull(articles, numberOfArticles);
        articleNumber = insertArticles(articles, articleNumber, numberOfArticles);
        break;
     case 2:
        System.out.println("Vilken artikel vill du ta bort?");
        removeArticle(articles);
        break;
     case 3:
        System.out.println("Visa artiklar");
        printArticles(articles);
        break;
     case 4:
        System.out.println("Vilken artikel vill du sälja? Hur stort antal vill du sälja?");
        sellArticle(sales, salesDate, articles);
        break;
     case 5:
        System.out.println("Orderhistorik");
        printSales(sales, salesDate);
        break;
     case 6:
        System.out.println("Avsluta");
        System.exit(0);
        break;
     default:
        System.out.print("Felaktig inmatning!\n");
        break;

When the user gives a string value then the programs says Wrong value then the program just stops. But when I select a number like 22 or something, the program says Wrong value and the loop continues and gives the user another chance to try. But when it comes to a string input it just stops and don't give the user another chance.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

To end the loop selection should equal to -1. I think changing the default case like below will solve the problem.

default:
        System.out.print("Felaktig inmatning!\n");
        selection = -1;
        break;

Then it will exit the loop when the user gives an incorrect value.

over 4 years ago · Santiago Trujillo Report

0

public static int input()
   {

      int input;

      input = 0;

      while (input == 0)
      {
         if (keyboard.hasNextInt())
         {
            input = keyboard.nextInt();
            break;
         } else
         {
            input = -1;
            break;

         }

      }

      return input;
   }
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!