I am trying to input a number between 1-10, if a number is entered which out of this range 3 consecutive times, the system should terminate. If the number is within the range, it should then prompt the user to enter names, which should match the number that was initially added. (So if 3 was inputted initially, the system to allow for 3 names to be added). May you direct me where I am going wrong?
import java.util.Scanner; public class Lab7{ public static void main(String []args){ Scanner in = new Scanner(System.in); int result; int count = 0; do { System.out.println("Enter number of students (Must be between 1-10)"); result = in.nextInt(); } while(result < 0 || result > 10); { System.out.println("Thank you, Please enter the names for the "+ result + " Students"); } try (Scanner input = new Scanner(System.in)) { System.out.print("Enter Full Name: "); String s1 = input.next(); System.out.print("The students name is" + " " + s1); } while(!(result < 0 || result > 10)); { System.out.println("wrong input"); count = count + 1; if (count == 3) { System.out.println("The maximum number of attempts exceeded"); System.exit(count); } } } }
Advertisement
Answer
You need to have the entire code in a while loop whose condition should depend on number of incorrect attempts ( count). Since you have not mentioned what needs to be done if the user enters the correct input ( say 3) ,i’m assuming it will take 3 names input and end ( in case you want to continue taking the names, remove the break condition mentioned in my code.
public class Lab7 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int result; int count = 0; while (count < 3) { System.out.println("Enter number of students (Must be between 1-10)"); result = in.nextInt(); // in.next(); if (result < 0 || result > 10) { count++; } else { System.out.println("Thank you, Please enter the names for the " + result + " Students"); int nameCount = 0; while (nameCount < result) { System.out.println("Enter Full Name: "); String s1 = in.next(); System.out.println("The students name is" + " " + s1); nameCount++; } break; } } } }
and the output is :
Enter number of students (Must be between 1-10) 2 Thank you, Please enter the names for the 2 Students Enter Full Name: john The students name is john Enter Full Name: jacob The students name is jacob