How can I get this to run another time? [duplicate] - java

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 1 year ago.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
final int STUDENT_SIZE = 50;
int i = 0;
char choice1 = 'y';
String [] stdntName = new String [50];
String [] WIDNUM = new String [STUDENT_SIZE];
int [] EXM1 = new int [STUDENT_SIZE];
int [] EXM2 = new int [STUDENT_SIZE];
int [] EXM3 = new int [STUDENT_SIZE];
int [] finalExm = new int [STUDENT_SIZE];
for (i=0; i < stdntName.length; i++) {
System.out.print("Please enter the name of Student " + (i+1) + ": ");
stdntName[i] = s.nextLine();
System.out.println("Please enter the WID of Student " + (i+1) + ": ");
WIDNUM[i] = s.nextLine();
if (WIDNUM[i].length() != 9 ) {
System.out.println("**Invalid WID...must be 9-digits");
System.out.println("Please re-enter score:");
WIDNUM[i] = s.nextLine();
}
System.out.println("Please enter score for Exam 1: ");
EXM1[i] = s.nextInt();
if (EXM1[i] < 0 || EXM1[i] > 50) {
System.out.println("**Invalid score...please enter 0-50 only");
System.out.println("Please re-enter score: ");
EXM1[i] = s.nextInt();
}
System.out.println("Please enter score for Exam 2 ");
EXM2[i] = s.nextInt();
if (EXM2[i] < 0 || EXM2[i] > 50) {
System.out.println("**Invalid score...please enter 0-50 only");
System.out.println("Please re-enter score: ");
EXM2[i] = s.nextInt();
}
System.out.println("Please enter score for Exam 3 ");
EXM3[i] = s.nextInt();
if (EXM3[i] < 0 || EXM3[i] > 50) {
System.out.println("**Invalid score...please enter 0-50 only");
System.out.println("Please re-enter score: ");
EXM3[i] = s.nextInt();
}
System.out.println("Please enter score for Final Exam ");
finalExm[i] = s.nextInt();
if (finalExm[i] < 0 || finalExm[i] > 100) {
System.out.println("**Invalid score...please enter 0-100 only");
System.out.println("Please re-enter score: ");
finalExm[i] = s.nextInt();
}
System.out.print("Do you wish to enter another? (y/n): ");
choice1 = s.nextLine().toLowerCase().charAt(0); // read entire line
if (choice1 != 'y') {
break;
}
}
}
}
This is the error message:
Do you wish to enter another? (y/n): Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48)
at java.base/java.lang.String.charAt(String.java:712)
at Proj4.main(Proj4.java:77)

Just add s.nextLine() because you scanner was not reaching the point to get your choice1
Your code fixed
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
final int STUDENT_SIZE = 50;
int i = 0;
char choice1 = 'y';
String [] stdntName = new String [50];
String [] WIDNUM = new String [STUDENT_SIZE];
int [] EXM1 = new int [STUDENT_SIZE];
int [] EXM2 = new int [STUDENT_SIZE];
int [] EXM3 = new int [STUDENT_SIZE];
int [] finalExm = new int [STUDENT_SIZE];
for (i=0; i < stdntName.length; i++) {
System.out.print("Please enter the name of Student " + (i+1) + ": ");
stdntName[i] = s.nextLine();
System.out.println("Please enter the WID of Student " + (i+1) + ": ");
WIDNUM[i] = s.nextLine();
if (WIDNUM[i].length() != 9 ) {
System.out.println("**Invalid WID...must be 9-digits");
System.out.println("Please re-enter score:");
WIDNUM[i] = s.nextLine();
}
System.out.println("Please enter score for Exam 1: ");
EXM1[i] = s.nextInt();
if (EXM1[i] < 0 || EXM1[i] > 50) {
System.out.println("**Invalid score...please enter 0-50 only");
System.out.println("Please re-enter score: ");
EXM1[i] = s.nextInt();
}
System.out.println("Please enter score for Exam 2 ");
EXM2[i] = s.nextInt();
if (EXM2[i] < 0 || EXM2[i] > 50) {
System.out.println("**Invalid score...please enter 0-50 only");
System.out.println("Please re-enter score: ");
EXM2[i] = s.nextInt();
}
System.out.println("Please enter score for Exam 3 ");
EXM3[i] = s.nextInt();
if (EXM3[i] < 0 || EXM3[i] > 50) {
System.out.println("**Invalid score...please enter 0-50 only");
System.out.println("Please re-enter score: ");
EXM3[i] = s.nextInt();
}
System.out.println("Please enter score for Final Exam ");
finalExm[i] = s.nextInt();
if (finalExm[i] < 0 || finalExm[i] > 100) {
System.out.println("**Invalid score...please enter 0-100 only");
System.out.println("Please re-enter score: ");
finalExm[i] = s.nextInt();
}
s.nextLine();
System.out.print("Do you wish to enter another? (y/n): ");
choice1 = s.nextLine().toLowerCase().charAt(0); // read entire line
if (choice1 != 'y') {
break;
}
}
}
}

Related

Java 3.6 Checking inputs

Ask the user to "Input a number: " 4 times.
If the input is not a number, ask again.
Output "success." after they have entered 4 numbers.
Please answer this code for me using while, if, if else and do statements.
int counter; System.out.print("Input a number: ");
while(!(scan.hasNextInt()));{
for (int i = 0; i < 3; i++){
scan.next();
System.out.print("Input a number: ");
if (!(pass.equals(pass2))) {
counter++;
} else if (!(scan.hasNextInt())) {
}
}
if (counter >= 2) {
System.out.println("Input a number: ");
}
} else if (!(scan.hasNextInt())) { System.out.println("success."); }
This is very basic stuff but I am struggling.
int[] inputIntegers = new int[4]; // Array to save input
Scanner scan = new Scanner(System.in);
int counter = 0;
while(counter < 4) {
System.out.println("Input a number: ");
String input = scan.next();
if(input.matches("[-]?[0-9]*")){ // Checking, if input is an integer
inputIntegers[counter]=Integer.parseInt(input); // Persing string to integer
counter++;
} else {
System.out.println("Input is not an integer");
}
}
System.out.println("Success");
scan.close(); //Do not forget do close scanner

How to loop a user input until integer is entered?

I want to run an interactive program where a user is prompted to enter a number of students. If the user inputs a letter or other character besides a whole number, they should be asked again ("Enter the number of students: ")
I have the following code:
public int[] createArrays(Scanner s) {
int size;
System.out.print("Enter the number of students: ");
size = s.nextInt();**
int scores[] = new int[size];
System.out.println("Enter " + size + " scores:");
for (int i = 0; i < size; i++) {
scores[i]=getValidInt(s,"Score " + (i + 1) + ": ");
}
return scores;
}
How can I create a loop for this?
Let's add a loop, take the value as String and check if it is a number:
String sizeString;
int size;
Scanner s = new Scanner(System.in);
do {
System.out.print("Enter the number of students: ");
sizeString = s.nextLine();
} while (!(sizeString.matches("[0-9]+") && sizeString.length() > 0));
size = Integer.parseInt(sizeString);
Try catching the exception and handling it until you get the desired input.
int numberOfStudents;
while(true)
{
try {
System.out.print("Enter the number of student: ");
numberOfStudents = Integer.parseInt(s.next());
break;
}
catch(NumberFormatException e) {
System.out.println("You have not entered an Integer!");
}
}
//Then assign numberOfStudents to the score array
int scores[] = new int[numberOfStudents]
try this
public int[] createArrays(Scanner s) {
int size;
System.out.print("Enter the number of students: ");
while(true) {
try {
size = Integer.parseInt(s.nextLine());
break;
}catch (NumberFormatException e) {
System.out.println();
System.out.println("You have entered wrong number");
System.out.print("Enter again the number of students: ");
continue;
}
}
int scores[] = new int[size];
System.out.println("Enter " + size + " scores:");
for (int i = 0; i < size; i++) {
scores[i]=getValidInt(s,"Score " + (i + 1) + ": ");
}
return scores;
}
int no1 = 0;
Scanner scanner = new Scanner(System.in);
while(true)
{
try {
System.out.print("Number 1: ");
no1 = Integer.parseInt(scanner.next());
break;
}
catch(NumberFormatException e) {
System.out.println("..You have not entered valid value!");
}
}

How to get the question to loop if the user input is incorrect

Whenever the user enters data that is incorrect, the program puts out a message telling the user to try again, but it then goes back to the main menu instead of letting the user try an input a different value. How can I do this?
public void createStudentRecord(Scanner in)
{
inputStudentID = null;
inputMark = 0;
System.out.println("Enter Student ID: ");
in.nextLine();
inputStudentID = in.nextLine();
if (!(inputStudentID.length()==6))
{
System.out.println("Enter a student ID that is 6 characters");
}
else
{
System.out.println("Enter Module Mark: ");
inputMark = in.nextInt();
if (inputMark <0 || inputMark >100)
{
System.out.println("PLease enter a module mark between 0-100");
}
else
{
addStudent(inputStudentID, inputMark);
System.out.println();
System.out.println("New student record has been " +
"successfully created");
System.out.println();
countRecords();
}
}
}
One way to do it is by looping until you see the correct/desired input. One problem with this kind of approach is that it will never terminate if user doesn't enter the expected values (if this is what you are looking for),
Code Snippet:
public void createStudentRecord(Scanner in) {
String inputStudentID = null;
int inputMark = 0;
while (true) {
System.out.println("Enter Student ID: ");
inputStudentID = in.nextLine();
if (!(inputStudentID.length() == 6)) {
System.out.println("Enter a student ID that is 6 characters");
} else {
break;
}
}
while (true) {
System.out.println("Enter Module Mark: ");
inputMark = Integer.parseInt(in.nextLine());
if (inputMark < 0 || inputMark > 100) {
System.out.println("PLease enter a module mark between 0-100");
} else {
break;
}
}
addStudent(inputStudentID, inputMark);
System.out.println("\nNew student record has been successfully created.\n");
countRecords();
}
There are two ways I would go about solving this problem. The first is to loop on each variable until a valid response is given.
public void createStudentRecord(Scanner in)
{
inputStudentID = null;
inputMark = -1;
while (inputStudentID == null)
{
System.out.println("Enter Student ID: ");
inputStudentID = in.nextLine();
if (inputStudentID.length() != 6)
{
System.out.println("Enter a student ID that is 6 characters");
inputStudentID = null;
}
}
while (inputMark == -1)
{
System.out.println("Enter Module Mark: ");
inputMark = in.nextLine();
if (inputMark < 0 || inputMark > 100) {
System.out.println("PLease enter a module mark between 0-100");
inputMark = -1;
}
}
addStudent(inputStudentID, inputMark);
System.out.println();
System.out.println("New student record has been successfully created");
System.out.println();
countRecords();
}
The second is to use recursion.
public void createStudentRecord(Scanner in)
{
inputStudentID = null;
inputMark = 0;
System.out.println("Enter Student ID: ");
inputStudentID = in.nextLine();
if (inputStudentID.length() == 6)
{
System.out.println("Enter a student ID that is 6 characters");
createStudentRecord(in);
return;
}
System.out.println("Enter Module Mark: ");
inputMark = in.nextLine();
if (inputMark < 0 || inputMark > 100)
{
System.out.println("PLease enter a module mark between 0-100");
createStudentRecord(in);
return;
}
addStudent(inputStudentID, inputMark);
System.out.println("\nNew student record has been successfully created\n");
countRecords();
}
Change the if-else statement to while statement.
public static void createStudentRecord(Scanner in)
{
inputStudentID = null;
inputMark = 0;
System.out.println("Enter Student ID: ");
in.nextLine();
inputStudentID = in.nextLine();
while (!(inputStudentID.length()==6))
{
System.out.println("Enter a student ID that is 6 characters");
}
System.out.println("Enter Module Mark: ");
inputMark = in.nextInt();
while (inputMark <0 || inputMark >100)
{
System.out.println("PLease enter a module mark between 0-100");
}
addStudent(inputStudentID, inputMark);
System.out.println();
System.out.println("New student record has been " +
"successfully created");
System.out.println();
countRecords();
}
Also, you can set a timeout variable to define the max number of times that user can try again. Such like,
public static void createStudentRecord(Scanner in)
{
int timeout1 = 3, timeout2 = 3;
inputStudentID = null;
inputMark = 0;
System.out.println("Enter Student ID: ");
in.nextLine();
inputStudentID = in.nextLine();
while (!(inputStudentID.length()==6))
{
System.out.println("Enter a student ID that is 6 characters");
--timeout1;
if( timeout1 == 0 ) {
System.out.println("say something here");
return;
}
}
System.out.println("Enter Module Mark: ");
inputMark = in.nextInt();
while (inputMark <0 || inputMark >100)
{
System.out.println("PLease enter a module mark between 0-100");
--timeout2;
if( timeout2 == 0 ) {
System.out.println("say something here");
return;
}
}
addStudent(inputStudentID, inputMark);
System.out.println();
System.out.println("New student record has been " +
"successfully created");
System.out.println();
countRecords();
}

How can I validate data from scanner (Java) [duplicate]

This question already has answers here:
validate an integer AND make it 5 digits
(4 answers)
Closed 4 years ago.
I need to ask the user to input a number from 1 to 10 then get the factorial of this number, I was able to do everything except to validation of the user name ( To be within range && not a string)
package test2;
import java.util.Scanner;
public class Test2 {
public static void main(String[] args) {
int userInput = 0 ;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number from 2 to 100");
if (sc.nextInt() < 101) {
userInput = sc.nextInt();
}
System.out.println(userInput);
}
}
one Method you can try is
public static void main(String[] args) {
int userInput = 0 ;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number from 2 to 100");
while (!sc.hasNextInt())
{
System.out.println("wrong input");
sc.next();
}
if (sc.nextInt() < 101) {
userInput = sc.nextInt();
}
System.out.println(userInput);
}
}
int userInput = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number from 2 to 100");
while (!sc.hasNextInt()) {
System.out.println("Please enter number");
sc.next();
}
while(true) {
userInput = sc.nextInt();
if (userInput > 2 && userInput < 100) {
break;
}else{
System.out.println("Please enter a number between 2 to 100");
}
}
System.out.println(userInput);
Or simply use a do-while
do {
userInput = sc.nextInt();
} while (userInput < 1 || userInput > 10);

the program is not executing as it should be?

this is my code
"the full code"
import java.util.Scanner;
import java.util.ArrayList;
public class RestTestGhada {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
RestGhada obj2 = new RestGhada("null",0,0,"null");
RestGhada obj3 = new RestGhada();
RestGhada obj4 = new RestGhada();
DateGhada obj5 = new DateGhada(19,8,1998);
DateGhada obj6 = new DateGhada(19,8,2011);
WorkerGhada obj7 = new WorkerGhada("Ghada","Alghamdi",obj5,obj6,"Female");
RestGhada obj8 = new RestGhada(12,"null",20,obj7);
obj2.setID(123456789);
System.out.print("Enter the number of employee: ");
int noemp=input.nextInt();
String empname[] = new String[5];
System.out.print("Enter the employee names: ");
for(int i=0;i<empname.length;i++)
empname[i]=input.nextLine();
obj2.setEmployeeName(empname);
System.out.print("**Menu** \n"
+ "1.Create three objects of restaurant.\n"
+ "2.Display all restaurants information.\n"
+ "3.Display the checkRestaurant result. \n"
+ "4.Exit.\n"
+ "Your choice is: ");
int choice =input.nextInt();
while(choice!=4){
switch(choice){
case 1: obj3.setName("null");obj3.setID(choice);obj4.setNoEmployee(noemp); break;
case 2: obj2.lastprint(); break;
case 3: obj2.CheckRestaurant(noemp); break;
}
System.out.print("\n Your choice: ");
choice=input.nextInt();
}
CorporateGhada[] ArrGroups=new CorporateGhada[4];
RestGhada obj1 = new RestGhada("KFC");
ArrayList<RestGhada>ALRestaurant=new ArrayList();
System.out.println("do you want to enter information?");
String c = input.nextLine();
while (true){
if(c.equals("no")||c.equals("No"))
break;
System.out.print("Menu\n"
+ "1.enter ID,name,number of employee,owner\n"
+ "2.enter ID,adress,name,owner,number of employee\n"
+ "your choice : ");
int choice1 =input.nextInt();
if(choice1 == 1){
System.out.println("Enter ID") ;
int ID=input.nextInt();
System.out.println("Enter name ") ;
String name=input.next();
System.out.println("nbemployee:") ;
int nbemployee =input.nextInt();
System.out.println("Enter owner:") ;
String owner=input.next();
ALRestaurant.add(new RestGhada(name,ID,nbemployee,owner));
}
else if (choice1 == 2){
System.out.println("Enter ID:");
int ID=input.nextInt();
System.out.println("Enter adrees:") ;
String adrees=input.next();
System.out.println("Enter name :");
String name=input.next();
System.out.println("Enter owner:") ;
String owner=input.next();
System.out.println("Enter nbemployee:");
int nbemployee=input.nextInt();
ALRestaurant.add(new RestGhada(ID,adrees,name,owner,nbemployee));
}
else
ALRestaurant.add(new RestGhada());
}
ALRestaurant.remove(1);
for(int i=0; i<ALRestaurant.size();i++ ){
System.out.print(ALRestaurant.get(i));}
System.out.print(ALRestaurant.contains(obj1));
}
}
when i try to run the first quistion doesn't take an answer and it get into the while loop directly.. i already take an information from the user before and it worked but now it's now..
when i run it it turns out like this :
do you want to enter information?
Menu
1.enter ID,name,number of employee,owner
2.enter ID,adress,name,owner,number of employee
your choice :
Did you type anything in the input before the first question was asked?
When I just run this (tried to turn your code into a working example) it waits for me to input:
public static void main(String[] args) {
ArrayList<RestGhada> ALRestaurant = new ArrayList();
Scanner input = new Scanner(System.in);
System.out.println("do you want to enter information?");
String c = input.nextLine();
while (true) {
if (c.equals("no") || c.equals("No"))
break;
System.out.print("Menu\n"
+ "1.enter ID,name,number of employee,owner\n"
+ "2.enter ID,adress,name,owner,number of employee\n"
+ "your choice : ");
int choice1 = input.nextInt();
if (choice1 == 1) {
System.out.println("Enter ID");
int ID = input.nextInt();
System.out.println("Enter name ");
String name = input.next();
System.out.println("nbemployee:");
int nbemployee = input.nextInt();
System.out.println("Enter owner:");
String owner = input.next();
ALRestaurant.add(new RestGhada(name, ID, nbemployee, owner));
} else if (choice1 == 2) {
System.out.println("Enter ID:");
int ID = input.nextInt();
System.out.println("Enter adrees:");
String adrees = input.next();
System.out.println("Enter name :");
String name = input.next();
System.out.println("Enter owner:");
String owner = input.next();
System.out.println("Enter nbemployee:");
int nbemployee = input.nextInt();
ALRestaurant.add(new RestGhada(ID, adrees, name, owner, nbemployee));
} else
ALRestaurant.add(new RestGhada());
}
}
private static class RestGhada {
public RestGhada(int id, String adrees, String name, String owner, int nbemployee) {
}
public RestGhada() {
}
public RestGhada(String name, int id, int nbemployee, String owner) {
}
}
In your code you haven't included your initialisation of the input object.
If you add the line
Scanner input = new Scanner(System.in);
In the beginning of your program it should work.
I ran your program with that line added and it worked.
Besides that you should really look up on correct indentation.
change to this code.
System.out.println("do you want to enter information (yse/no) ? :");
String c = input.nextLine();
while (true) {
if (c.equals("no") || c.equals("No")){
break;
}
else{
System.out.println("Enter Your Choice(1 or 2) :");
int choice1 = input.nextInt();
if (choice1 == 1) {
System.out.println("Enter ID");
int ID = input.nextInt();
System.out.println("Enter name ");
String name = input.next();
System.out.println("nbemployee:");
int nbemployee = input.nextInt();
System.out.println("Enter owner:");
String owner = input.next();
ALRestaurant.add(new RestGhada(name, ID, nbemployee, owner));
} else if (choice1 == 2) {
System.out.println("Enter ID:");
int ID = input.nextInt();
System.out.println("Enter adrees:");
String adrees = input.next();
System.out.println("Enter name :");
String name = input.next();
System.out.println("Enter owner:");
String owner = input.next();
System.out.println("Enter nbemployee:");
int nbemployee = input.nextInt();
ALRestaurant.add(new RestGhada(ID, adrees, name, owner, nbemployee));
} else{
ALRestaurant.add(new RestGhada());
}
}
}

Categories