mercredi 23 janvier 2019

How to write a program which can continuously ask users for inputs until the inputs meet a specific requirement to run the code?

I have to write a program that starts by requesting an integer in the range 0 < N < 20. Numbers outside this range are rejected and a new request is made. Output the sum of the sequence of numbers starting at 1 and ending with N. I have got most of the codes but I can not continuously ask users for inputs until an input meets the requirement. I tried to use "return" in line 11, however, it does not go back into the loop after getting another input. What should I do now?

import java.util.*;
class ExamTesterNine{
  public static void main(String args[]){
   Scanner kbReader= new Scanner(System.in);
   int num=kbReader.nextInt();
   System.out.println("Enter an integer smaller than 20 and larger than 0");
   int result;
   int sum=0;

   if (!(num>0&&num<20)){
     return;
   }else{
     for(int i=1; i<=num; i++)
   sum=sum+i;

   int [] number= new int [num];
   for (int a=0; a<(number.length-1); a++ ){
     number[a]=a+1;
     System.out.print(number[a]+"+");}
   System.out.print(num+"="+sum);
   }

  }
}

Aucun commentaire:

Enregistrer un commentaire