Java 2D Seating Array for a Theater - java

import java.util.*;
/**
* Write a description of class TheaterApp here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class TheaterApp {
static int [][] seats = {
{10,10,10,10,10,10,10,10},
{10,10,10,10,10,10,10,10},
{10,10,20,20,20,20,10,10},
{20,20,30,30,30,30,20,20},
{30,30,40,40,40,40,30,30},
{30,40,40,50,50,40,40,40}};
/**
* Constructor for objects of class TheaterApp
*/
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
String ans;
do {
System.out.print("Enter request, please (or 'help' or 'quit') ");
ans = input.next();
if (ans.equals("help")) {
System.out.println("Possible commands");
System.out.println("price <price>");
System.out.println("seat <row> <seat>");
System.out.println("left");
System.out.println("remaining <price>");
System.out.println("print");
System.out.println("quit");
System.out.println("help");
} else if (ans.equals("price")) {
int p = input.nextInt();
for (int i = 0; i < seats.length; i++) {
for (int j = 0; j < seats[i].length; j++) {
if (seats[i][j] == 0) {
System.out.println("Next available seat at position: " + i + " " + j);
}
}
}
// Find the 'best' seat at the given price
} else if (ans.equals("seat")) {
int r = input.nextInt();
int c = input.nextInt();
int k;
int i;
int j;
for (int l = 0; l < 6; l++) {
k = 1;
for(i=0;i<6;i++) {
for(j=0;j<8;j++) {
if (k == input.nextInt()) {
// check if the seat has already been reserved
if (seats[i][j]== 0) {
System.out.println("That seat has already been reserved");
}
// if its not reserved then reserve it
else {
seats[i][j]= 0;
}
}
k++;
System.out.println(seats[i][j]);
}
}
}
// Reserve the given row and seat, if possible
} else if (ans.equals("left")) {
// Print the total available seats
} else if (ans.equals("remaining")) {
int p = input.nextInt();
// Print the total available seats at this price
} else if (ans.equals("print")) {
for (int r = 0; r < seats.length; ++r) {
for (int s = 0; s < seats[r].length; ++s) {
System.out.print(seats[r][s] + " ");
}
System.out.println();
}
} else if (!ans.equals("quit")) {
System.out.println("Come again?");
}
} while (!ans.equals("quit"));
System.out.println("Good bye");
}
}
This array represents theater seats and I have to mark sold seats by changing the price to 0. I also have to make sure seats are open when a user asks for a a certain spot, and when a user enters a price, find any seats that are open.
So I'm pretty sure I figured out the code for finding the best seat at any given price. I can't figure out how to do the remaining code.
I just need to find out how to print the total available seats and also how to print the total available seats when a certain price is entered.
Thanks.

You'd just use nested for loops, like you did before, except now you'd have some kind of a availableSeats counter you'll increment every time a seat meets a certain condition.
Like so:
int availableSeats = 0;
for(i=0;i<6;i++) {
for(j=0;j<8;j++) {
if(seats[i][j] == sometargetprice){
availableSeats++;
}
}
}
System.out.println("Total of " + availableSeats + " are available.");
Unless I'm not understanding the problem correctly.

Related

How to print two different data type arrays?

Can anyone help?
Choice 2 isn't working. It is suppose to display the employee ID when the user inputs the employee Name, but when the user enters the name nothing prints. The code has no errors.
public static void main(String[] args) {
int[] emplID={ 42577, 38611, 32051, 28627, 42061, 79451 };//employee ID
int ID = employeeID(emplID);
String[] emplNames= { "Bruce Wayne", "Barry Allen", "Hal Jordan", "Dinah Lance", "Oliver Queen", "Tineil Charles" };// Employee Names
search(emplNames, emplID);
//methods called from main
}
public static int employeeID(int [] emplID) {
//check ID length
for(int i=0; i< emplID.length; i++) {
if((emplID[i] > 10000)&&(emplID[i] < 99999)) {
System.out.print(emplID[i] + " - Valid ID length\n");
}
else {
System.out.println(emplID[i] + " - Invalid ID! ID must be Five digits!\n");
}//end of check length
//check if ID is prime
boolean isPrime = true;
for (int j = 2; j < emplID[i]; j++) {
if (emplID[i] % j == 0) {
System.out.println(emplID[i] + " - not prime");
isPrime = false;
break;
}
}
if(isPrime) System.out.println(emplID[i] + " - valid prime");//end of check prime
}//end of employeeID method
return 0;
}// end of ID checker
// search employee data
public static void search(String[] emplNames, int[]emplID) {
Scanner scan= new Scanner(System.in);
//Menu Choice
System.out.println("Please choose 1 to enter Employee ID or 2 to enter Employee Name:" );
int num = scan.nextInt();//input choice
// Choice 1 to enter ID to display name
if (num == 1) {
System.out.println("Please enter Employee ID:");
int searchID= scan.nextInt();
for(int ID = 0; ID < emplID.length; ID++) {
if (searchID == (emplID[ID])){
System.out.println("Name: "+ emplNames[ID]);
}
}
}
// Choice 2 to enter name to display ID
else if(num == 2) {
System.out.println("Please enter Employee Name");
String searchName= scan.next();
for(int ID = 0; ID< emplID.length; ID++){
if ((searchName.equals(emplNames[ID]))){
System.out.println("ID: " + emplID[ID]);
}
}
}
else
System.out.println("Employee Not Found");
}
}
I copied and pasted your code and ran it on my machine. Yes, choice 2 was not working for me either.
Before reading your code completely my gut feeling was that the cause of failure was in using the Scanner class to get the name of the employee. I have had similar issues in the past and the best move is to learn to use the InputStreamReader and BufferedStreamReader objects.
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
1: I didn't do anything to your main()
public static void main(String[] args) {
int[] emplID={ 42577, 38611, 32051, 28627, 42061, 79451 };//employee ID
int ID = employeeID(emplID);
String[] emplNames= { "Bruce Wayne", "Barry Allen", "Hal Jordan", "Dinah Lance", "Oliver Queen", "Tineil Charles" };// Employee Names
search(emplNames, emplID);
}
2: I didn't do anything to your employeeID() function
public static int employeeID(int [] emplID) {
//check ID length
for(int i=0; i< emplID.length; i++) {
if((emplID[i] > 10000)&&(emplID[i] < 99999)) {
System.out.print(emplID[i] + " - Valid ID length\n");
}
else {
System.out.println(emplID[i] + " - Invalid ID! ID must be Five digits!\n");
}//end of check length
//check if ID is prime
boolean isPrime = true;
for (int j = 2; j < emplID[i]; j++) {
if (emplID[i] % j == 0) {
System.out.println(emplID[i] + " - not prime");
isPrime = false;
break;
}
}
if(isPrime) System.out.println(emplID[i] + " - valid prime");//end of check prime
}//end of employeeID method
return 0;
}// end of ID checker
3: It's in your search() method where I first created the InputStreamReader and the BufferedReader:
public static void search(String[] emplNames, int[]emplID) {
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader buff = new BufferedReader(in);
//Menu Choice
System.out.println("Please choose 1 to enter Employee ID or 2 to enter Employee Name:" );
int num = 0;
try {
num = Integer.parseInt(buff.readLine());
} catch (Exception e) {
e.printStackTrace();
}
4: Since choice 1 works fine, all I did was change your for loop to a for-each loop to make it easier to read.
// Choice 1 to enter ID to display name
if (num == 1) {
System.out.println("Please enter Employee ID:");
int searchID = 0;
try {
searchID = buff.read();
} catch (Exception e) {
e.printStackTrace();
}
for (int i : emplID) {
if (searchID == i) {
System.out.println("Name: " + emplNames[i]);
}
}
5: Here is what I did to make your 2nd Option work. Again, get the String from user via BufferedReader object's readLine() method. Then, it was just letting your for-loop searching for a match. That's it. Afterward, I ran the program and tested it for all the names you had above, works fine.
} else if (num == 2) {
System.out.println("Please enter Employee Name");
String searchName = "";
try {
searchName = buff.readLine();
} catch(Exception e) {
e.printStackTrace();
}
for(int ID = 0; ID< emplID.length; ID++){
if ((searchName.equals(emplNames[ID]))){
System.out.println("ID: " + emplID[ID]);
}
}
} else {
System.out.println("Employee Not Found");
}
}
}
6: Yeah, Scanner has an issue where it either doesn't read the entire line or you need to flush the stream before getting the input. It caused a lot of problems for me in a bunch of easy programs. Then I switched to using the InputStreamReader and BufferedStreamReader combo. Just wrap them in try-catch blocks, and you're fine. Look into it, it will the behavior of your code and your life a lot easier.
7: I hope this was helpful.

How can I update the data inside of an array to be false instead of true?

This program is to reserve time available from three different games. So far in the program, I had printed the two different menus on that shows the game and the other one shows the available time Slots. the Program is set to be an infinite loop so other users have the chance to pick a game and reserve time as well. This is where my problem comes, the second time the program runs it stills displays the time that was previously picked.
import java.util.Scanner;
public class GameReservationSystem {
public static Scanner input = new Scanner(System.in);
static String[] timeSlots = {"1-2pm", "2-3pm", "3-4pm", "4-5pm"};
static String[] Games = {"Backganmon", "Chess", "Dominoes"};
static boolean avaliableTime[][] = new boolean[Games.length][timeSlots.length];
static int userChoice;
public static void main(String[] args) {
for (int i = 0; i < Games.length; i++) {
for (int j = 0; j < timeSlots.length; j++) {
avaliableTime[i][j] = true;
}
}
mainMenu();
}
public static void mainMenu() {
while (true) {
characterPrint('-');
for (int i = 0; i < Games.length; i++) {
System.out.print(i + ". ");
System.out.println(Games[i]);
}
characterPrint('-');
System.out.println("input a number to choose your game!");
userChoice = input.nextInt();
reserveMenu(userChoice);
}
}
public static void reserveMenu(int userChoice) {
int reserveTime = 0;
if (userChoice >= 0 && userChoice < Games.length) {
characterPrint('-');
System.out.println("This are the avaliable times to play" + Games[userChoice]);
for (int i = 0; i < timeSlots.length; i++) {
System.out.print(i + ". ");
System.out.println(timeSlots[i]);
}
characterPrint('-');
System.out.println("Input a number to reserve a time: ");
reserveTime = input.nextInt();
}
if (reserveTime >= 0 && reserveTime < timeSlots.length) {
avaliableTime[userChoice][reserveTime] = false;
System.out.println("You have succesfully reserve a time to play " + Games[userChoice] + " at" + timeSlots[reserveTime]);
}
}
public static void characterPrint(char c) {
for (int i = 0; i < 30; i++) {
System.out.print(c);
}
System.out.println();
}
}
In fact, your problem isn't that you didn't change the boolean values in your table from true to false. Instead, your problem is that you didn't use information in the table before you make reservations. What you were doing is to always set that value to false and print "succesfully reserve", without checking whether that time has already been reserved by someone else.
Try the following code. I also add some codes to handle invalid input number.
By the way, "avaliableTime" looks like a typo, so I changed it to "availableTime".
import java.util.Scanner;
public class GameReservationSystem {
public static Scanner input = new Scanner(System.in);
static String[] timeSlots = {"1-2pm", "2-3pm", "3-4pm", "4-5pm"};
static String[] Games = {"Backganmon", "Chess", "Dominoes"};
static boolean availableTime[][] = new boolean[Games.length][timeSlots.length];
static int userChoice;
public static void main(String[] args) {
for (int i = 0; i < Games.length; i++) {
for (int j = 0; j < timeSlots.length; j++) {
availableTime[i][j] = true;
}
}
mainMenu();
}
public static void mainMenu() {
while (true) {
characterPrint('-');
for (int i = 0; i < Games.length; i++) {
System.out.print(i + ". ");
System.out.println(Games[i]);
}
characterPrint('-');
System.out.println("input a number to choose your game!");
userChoice = input.nextInt();
reserveMenu(userChoice);
}
}
public static void reserveMenu(int userChoice) {
int reserveTime = 0;
if (userChoice >= 0 && userChoice < Games.length) {
characterPrint('-');
System.out.println("This are the avaliable times to play" + Games[userChoice]);
for (int i = 0; i < timeSlots.length; i++) {
if (availableTime[userChoice][i]) {
//if false, this time is not available and should not be displayed.
System.out.print(i + ". ");
System.out.println(timeSlots[i]);
}
}
characterPrint('-');
System.out.println("Input a number to reserve a time: ");
reserveTime = input.nextInt();
}else {
//handle unexpected game number.
System.out.println("Invalid game number, please try again.");
}
if (reserveTime >= 0 && reserveTime < timeSlots.length) {
//what if someone typed 0 although 0 wasn't displayed? (0 wasn't displayed, for example, because it has been reserved by someone else.)
//So you should check whether it is available by the following line.
if (availableTime[userChoice][reserveTime]) {
//if true, this time hasn't been reserved, so it is a valid input.
availableTime[userChoice][reserveTime] = false;
System.out.println("You have succesfully reserve a time to play " + Games[userChoice] + " at" + timeSlots[reserveTime]);
}else {
//if already false, this time has already been reserved by someone else,
//thus it is an invalid input.
System.out.println("This time has already been reserved, please try again.");
}
}else {
System.out.println("Invalid time number, please try again.");
}
}
public static void characterPrint(char c) {
for (int i = 0; i < 30; i++) {
System.out.print(c);
}
System.out.println();
}
}

Random numbers in array, user input number. If appears in array, user gets points

I know how to create the array as i did below. But how would i check if the user inputed the same number. I tried using if statements but i kept getting errors. I also tried using a do while.
I have to write a program that generates and stores 20 random numbers in the array Data[] and asks the user to enter their guess which i did. If their number appears in the array, they get 2 points for each occurrence, the array is printed and all positions where the lucky number can be found. If it doesn't appear in the array, I have to print the lowest and highest values of the array and allow only one more try. if the player gets it right the second time they get 1 point for each appearance.
int lucky;
int Data[]= new int[20];
for(int i=0;i<Data.length;i++){
Data[i]=(int)(Math.random()*100);
}
for(int i=0;i<Data.length;++i){
System.out.println(Data[i]+"\t");
}
String input1=JOptionPane.showInputDialog("Enter your lucky number");
lucky=Integer.parseInt(input1);
System.out.println(lucky);
Something like this should work as you expect to see if the value exists in the array, it can be expanded to search and find for high/low values:
int counter = 0; //Assume not found at first
for (int i: Data) {
if (i==Integer.parseInt(input1)){
counter++;
}
}
System.out.println("The numer was found "+Integer.toString(counter)+" time(s).");
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] data = new int[20];
int guess;
int times;
int score = 0;
int tries = 0;
fillArrayWithRandoms(data);
while (tries < 2) {
System.out.print("Guess a number: ");
guess = sc.nextInt();
if ((times = timesInArray(guess, data)) != 0) {
if (tries == 0)
score += 2 * times;
else
score += times;
printArray(data);
fillArrayWithRandoms(data);
System.out.println("You are lucky! Score: " + score + "\n");
} else {
tries++;
System.out.println("You are unlucky!");
if (tries < 2)
printBoundaries(data);
System.out.println();
}
}
System.out.println("Game Over! Your score: " + score);
}
private static void printArray(int[] data) {
for (int element : data) {
System.out.print(element + " ");
}
System.out.println();
}
private static void fillArrayWithRandoms(int[] data) {
for (int i = 0; i < data.length; i++) {
data[i] = (int) (Math.random() * 100);
}
}
private static int timesInArray(int guess, int[] data) {
int occurrence = 0;
for (int element : data) {
if (element == guess)
occurrence++;
}
return occurrence;
}
private static void printBoundaries(int[] data) {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int element : data) {
if (element < min) {
min = element;
}
if (element > max) {
max = element;
}
}
System.out.println("Try a number between " + min + " and " + max);
}
}

Problems with my for loops printing out my arrays

can anybody help me figure out why my for loops cant print the right answer out.
Its like its skipping the first array number [0]. but if i try to make it print out my Array nr [1] out it works fine.
It must be somthing with my counter ans answer at the top.
package assignment9.pkg1;
import java.util.Scanner;
/**
*
* #author Anders
*/
public class Assignment91 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String studName = "Anders";
int counter = 1;// i think the problem is here
int answer = 1; // same
System.out.println(" welcome to student database, show informations about student" + studName);
Scanner courseScan = new Scanner(System.in);
Scanner gradeScan = new Scanner(System.in);
Scanner answerScan = new Scanner(System.in);
System.out.println(" Enter the name of courses");
String[] courseArray = new String[counter];
int[] gradeArray = new int[counter];
for (int k = 0; k <= counter; k++) {
if (counter < 20) {
while (answer != 0) { // what have i done here with that 0 answer??
System.out.println(" enter name");
courseArray[k] = courseScan.nextLine();
System.out.println(" Enter grade");
gradeArray[k] = gradeScan.nextInt();
System.out.println(" Do you want to add one more course enter 1, if not enter 0");
answer = answerScan.nextInt();
}
} else {
System.out.println("Sorry, there is no more memory");
}
}
int n = gradeArray.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (gradeArray[j - 1] > gradeArray[j]) {
//swap the elements!
temp = gradeArray[j - 1];
gradeArray[j - 1] = gradeArray[j];
gradeArray[j] = temp;
// Swap the course array
String gradeArrayTemp;
gradeArrayTemp = courseArray[j - 1];
courseArray[j - 1] = courseArray[j];
courseArray[j] = gradeArrayTemp;
}
}
}
for (int l = 0; l < courseArray.length; l++) {
System.out.println("grade " + gradeArray[l] + "name " + courseArray[l]); // why does it not print all the array out
}
Scanner request = new Scanner(System.in);
System.out.println(" what do you want to do. Enter 1 to rename a course");
System.out.println(" enter 2 to change a grade ");
int regNumber = request.nextInt();
switch (regNumber) {
case 1: // rename a course
Scanner search = new Scanner(System.in);
System.out.println("Enter the name of the course you want to rename");
String searchCourse = search.nextLine();
for (int i = 0; i < courseArray.length; i++) {
if (searchCourse.equals(courseArray[i])) {
System.out.println("Yes there is a course named " + courseArray[i]);
System.out.println(" to change coursename insert new name");
// here i change the coursename
Scanner newName = new Scanner(System.in);
courseArray[i] = newName.nextLine();
} else {
System.out.println(" no record of this course");
}
System.out.println(" you have chosen to rename course into " + courseArray[i]);
}
}
}
}
In this section of the code:
for (int k = 0; k <= counter; k++) {
if (counter < 20) {
while (answer != 0) { // what have i done here with that 0 answer??
System.out.println(" enter name");
courseArray[k] = courseScan.nextLine();
System.out.println(" Enter grade");
gradeArray[k] = gradeScan.nextInt();
System.out.println(" Do you want to add one more course enter 1, if not enter 0");
answer = answerScan.nextInt();
}
} else {
System.out.println("Sorry, there is no more memory");
}
}
note that you have used k to insert into array. the k do not update because is stuck in the inner while loop There for use another counter.
Also here
String[] courseArray = new String[counter];
you use counter to create the array. Which is 1. You are creating one eliment array.
You code will work like this:
int k = 0;
if (counter < 20) {
while (answer != 0) { // what have i done here with that 0 answer??
System.out.println(" enter name");
courseArray[k] = courseScan.nextLine();
System.out.println(" Enter grade");
gradeArray[k] = gradeScan.nextInt();
System.out.println(" Do you want to add one more course enter 1, if not enter 0");
answer = answerScan.nextInt();
k++;
}
} else {
System.out.println("Sorry, there is no more memory");
}
And
for (int i = 0; i < courseArray.length; i++) {
if(courseArray[i] != null)
System.out.println("grade " + gradeArray[i] + "name " + courseArray[i]); // why does it not print all the array out
}
I have assumed that you take only 20 records depending on the loop. So i initiated arrays
String[] courseArray = new String[20];
int[] gradeArray = new int[20];

How do you make sure user input are integers only?

I did everything as far as concepts. I made my class, and my client class. The assignment is to make a program that allows the user to input 10 grades into a gradebook, and get the max, min, and average grade of class.
My only problem is I want to make sure the user cannot put anything in the program that is not an integer; do I put instructions like that in my class or client java doc?
This is my class:
import java.util.Arrays;
public class ExamBook{
int grades[];
int classSize;
int MIN = 0;
int MAX = 100;
public ExamBook(int[] gradeBook)
{
classSize = 10;
//instantiate array with same length as parameter
grades = new int[gradeBook.length];
for ( int i = 0; i <= gradeBook.length-1; i++ )
{
grades[i] = gradeBook[i];
}
Arrays.sort(grades);
}
//setter, or mutator
public void setClassSize( int newClass )
{
classSize = newClass;
}
//get return method
public int getClassSize()
{
return classSize;
}
//calculate highest grade
public int calculateMaxGrade()
{
int max = grades[0]; //assuming that the first index is the highest grade
for ( int i = 0; i <= grades.length - 1; i++ )
{
if ( grades[i] > max )
max = grades[i]; //save the new maximum
}
return max;
}
//calculate lowest grade
public int calculateMinGrade()
{
int min = grades[0]; //assuming that the first element is the lowest grade
for ( int i = 0; i <= grades.length - 1; i++ )
{
if ( grades[i] < min)
min = grades[i]; //save the new minimum
}
return min;
}
//calculate average
public double calculateAverageGrades()
{
double total = 0;
double average = 0;
for ( int i = 0; i < grades.length; i++ )
{
total += grades[i];
}
average = total/grades.length;
return average;
}
//return an assorted array
public int[] assortedGrades()
{
Arrays.sort(grades);
return grades;
}
//return printable version of grades
#Override
public String toString()
{
String returnString = "The assorted grades of the class in ascending order is this: " + "\t";
for ( int i = 0; i <= grades.length - 1; i++ )
{
returnString += grades[i] + "\t";
}
returnString += " \nThe class average is a/an " + calculateAverageGrades() + "." + "\nThe highest grade in the class is " + calculateMaxGrade() + "." + "\nThe lowest grade in the class is " + calculateMinGrade() + ".";
returnString += "\n";
return returnString;
}
}
**This is my client:**
import java.util.Scanner;
import java.util.Arrays;
public class ExamBookClient
{
public static ExamBook classRoom1;
public static void main( String[] args)
{
int MAX = 100;
int MIN = 0;
Scanner scan = new Scanner(System.in);
//create array for testing class
int[] grading = new int [10];
System.out.println("Please enter 10 grades to go into the exam book.");
if(scan.hasNextInt())
{
for (int i = 0; i < grading.length; i++)
{
int x = scan.nextInt();
if( x>MIN && x<MAX)
{
grading[i] = x;
}
}
}
classRoom1 = new ExamBook (grading);
System.out.println("The classroom size is " + classRoom1.getClassSize() + "."
+ "\n" + classRoom1.toString() + ".");
}
}
Prompt for scan.hasNextInt() in your for loop of your client instead of outside the for loop. Like this:
boolean failed = false;
for (int i = 0; i < grading.length; i++)
{
if (failed)
scan.nextLine();
failed = false;
if (scan.hasNextInt()) {
int x = scan.nextInt();
if(x >= MIN && x <= MAX)
{
grading[i] = x;
} else {
System.out.println("Grade must be from 0-100!");
i--;
continue;
}
} else {
// jump back to the start of this iteration of the loop and re-prompt
i--;
System.out.println("Number must be an int!");
failed = true;
continue;
}
}
You might want to do this in two parts - your API should specify that it works with only integers - perhaps the method which processes the grades will accept Integer arguments only. The parser of the String can specify in its Javadocs what it does when the argument passed to it is not an integer. You client should also validate that the input is an integer (maybe within the valid range). If the user input is incorrect, then maybe it can display a usage manual.
You can check using the below code. If you pass other than number it would throw NumberFormatException
public static boolean checkIfNumber(String input) {
try {
Integer in = new Integer(input);
} catch (NumberFormatException e) {
return false;
}
return true;
}
You can change this part as follows. This way the user can enter non-integers but in those cases you will print out warnings and you will ignore them.
System.out.println("Please enter 10 grades to go into the exam book.");
int i = 0;
int x = -1;
while (scan.hasNext() && i < 9) {
String sx = scan.next();
try {
x = Integer.parseInt(sx);
i++;
if (x > MIN && x < MAX) {
grading[i] = x;
}
} catch (NumberFormatException e) {
System.out.println("Not an integer.");
}
}
classRoom1 = new ExamBook(grading);
Chech this link, it has the solution.
You must use the method hasNextInt() of Scanner.
If you do not want to use exceptions you can always use a Regex match to check that what you have in the string is a number valid for you.
Bearing in mind that your valid numbers are between 0 and 100, and 0 and 100 are not included seeing you code, the reg ex will be:
s.matches("[1-9][0-9]{0,1}")
Basically what this means is that you are going to have a character that is a number between 1 and 9 as first char, and then you could have one between 0 and 9, this way you do not allow 0 at the beginning (01 is not valid) and 0 by it self is also not valid. 100 has 3 chars so is not valid neither.

Categories

Resources