2D array String split error - java

So basically my program takes a text file and reads the file and splits it into a 2D array (Textfile: http://pastebin.com/6ACSUL20). I pass the name of the text file in the command line. However, when I run my program I get an ArrayIndexOutOfBoundsException which leads me to believe that the program did not split the text file correctly. Pointing me to every method that contains Integer.parseInt(titanic[i][1]) Any help would be appreciated.
package testtitanic;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.File;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
public class Titanic {
String[][] titanic;
public Titanic(String[] args){
try{
File text = new File(args[0]);
//turns the txt file into a string
String content = new Scanner(text).useDelimiter("\\Z").next();
//creates array and breaks up by new lines
String[] rows = content.split("\n");
// creates 2D array
this.titanic = new String[rows.length][];
// fills 2D array
for(int i = 0; i < rows.length; i++){
this.titanic[i] = rows[i].split("\\t");
}// end for loop
}// end try
catch(FileNotFoundException e){
System.out.println("Error" + e.getMessage());
}// end catch method
}// end fill method
public void menu(){
System.out.println("*******Welcome to the Titanic Statistical Application**************");
System.out.println("");
System.out.println("Enter the number of the question you want answered. Enter 'Q' to quit program:");
System.out.println("");
System.out.println("1. How many passengers were on the Titanic?");
System.out.println("2. What percent of passengers perished on the Titanic?");
System.out.println("3. What percent of passengers survived the sinking of the Titanic?");
System.out.println("4. What percentage of passengers survived for each of the three classes?");
System.out.println("5. What specific passengers who were less than 10 years old survived the sinking of the titanic?");
System.out.println("6. For each letter in the alphabet, how many passengers last names started with that letter?");
System.out.println("7. How many females and males were on the Titanic?");
System.out.println("Q. Quit the program");
}
public void getPassengerNumber(){
int num = titanic.length;
System.out.println("There were " + num + " passengers on the Titanic.");
}//end method
public void getPerishedPercent(){
int num = titanic.length;
int perished = 0;
for(int i = 0; i < num; i++){
int x = Integer.parseInt(titanic[i][1]);
if(x == 0){
++perished;
}// end if
}// end for
double percent = (perished / num) * 100;
System.out.println("The percentage perished on the Titanic is: " + percent);
}// end method
public void getPerishedSurvived(){
int num = titanic.length;
int survived = 0;
for(int i = 0; i < num; i++){
int x = Integer.parseInt(titanic[i][1]);
if(x == 1){
++survived;
}// end if
}// end for
double percent = (survived / num) * 100;
System.out.println("The percentage survived on the Titanic is: " + percent);
}// end method
public void getClassPercentage(){
int firstClass = 0;
int secondClass = 0;
int thirdClass = 0;
int num = titanic.length;
for(int i = 0; i < titanic.length; i++ ){
int x = Integer.parseInt(titanic[i][0]);
if(x == 1){
++firstClass;
}// end iff
if(x == 2){
++secondClass;
}
if(x == 3){
++thirdClass;
}
}// end for
double firstpercent = (firstClass / num) * 100;
double secondpercent = (secondClass / num) * 100;
double thirdpercent = (thirdClass / num) * 100;
System.out.println("Percent Survived for Firstclass is: " + firstpercent);
System.out.println("Percent Survived for Secondclass is: " + secondpercent);
System.out.println("Percent Survived for ThirdClass is: " + thirdpercent);
}// end method
public void getAge() {
int num = titanic.length;
int age = 0;
for(int i = 0; i < num; i++ ){
int x = Integer.parseInt(titanic[i][4]);
if(x < 10){
System.out.println(titanic[i][2]);
}
}// end for loop
}// end method
public void getLetters(){
for(char a = 'A'; 'Z' <= a; a++ ){
int temp = 0;
for(int i = 0; i < titanic.length; i++){
char x = titanic[i][2].charAt(0);
if(x == a){
++temp;
}// end if
System.out.println(a + ": There are " + temp + " passengers that have this letter to start as their last name.");
}// end inner
} // end outer
}// end method
public void getGender(){
int male = 0;
int female = 0;
int num = titanic.length;
for(int i = 0; i < num; i++){
if(titanic[i][3].equals("female")){
++female;
}// end if
if(titanic[i][3].equals("male")){
++male;
}// end if
}// end for
System.out.printf("There were %d females and %d males on the titanic \n", male, female);
}// end method
}//end class Titanic
Using this class to call
package testtitanic;
import java.time.LocalTime;
import java.time.Duration;
import java.util.Scanner;
/**
*
* #author Joe
*/
public class TestTitanic {
/**
* #param args the command line arguments
*/
public static void main(String[] argv) {
LocalTime startTime = LocalTime.now();
Scanner input = new Scanner(System.in);
int y = 1;
Titanic data = new Titanic(argv);
while(y == 1){
data.menu();
char x = input.next().charAt(0);
switch (x){
case '1':
data.getPassengerNumber();
break;
case '2':
data.getPerishedPercent();
break;
case '3':
data.getPerishedSurvived();
break;
case '4':
data.getClassPercentage();
break;
case '5':
data.getAge();
break;
case '6':
data.getLetters();
break;
case '7':
data.getGender();
break;
case 'Q':
y = 0;
break;
default:
System.out.println("Please enter a valid input to exit, be sure to input a capital Q.");
}// end switch
}// end while loop
LocalTime endTime = LocalTime.now();
Duration timeElapsed = Duration.between(startTime,endTime);
double time = timeElapsed.toMillis() * 1000;
System.out.println("Thanks for running this program the total time elapsed is: " + time + " seconds");
}
}

Worked for me, but I hardcoded the filename in the Titanic constructor. Are you sure you're passing it a filename?
Can you post the stack trace? Is the array index out of bounds on argv?
You don't need to guess where the index is out of bounds is. The stack trace will tell you the exact line.

Related

Creating a method which specifically calculates the average of the users entered values

I am making a program which allows the user to look at student's grades, find the average, find the highest grade, the lowest etc. For one of the methods I have, it checks for the average of the values that the user entered. I tried to do this but to no avail. Here is the specific code:
public static void classAvg(int numOfKids) {
int average = 0;
for (int i = 0; i < numOfKids; i++) {
average += studentGrade[i];
}
average = (average/numOfKids) * 100;
System.out.println("The average of the class will be " + average + "%");
}
For some better context, here is the rest of the code:
import java.util.Scanner;
public class StudentGradeArray {
static Scanner input = new Scanner(System.in);
static String[] studentName;
static String letterGrade = " ";
static int[] studentGrade;
static int gradeMax = 0;
static int gradeMin = 0;
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("How many students are you entering into the database?");
int numOfKids = input.nextInt();
studentGrade = new int[numOfKids];
studentName = new String[numOfKids];
for (int i = 0; i < numOfKids; i++) {
System.out.println("Enter the student's name:");
studentName[i] = input.next();
System.out.println("Enter " + studentName[i] + "'s grade");
studentGrade[i] = input.nextInt();
}
do {
System.out.println("");
System.out.println("Enter a number for the following options:");
System.out.println("");
System.out.println("1. Student's letter grade");
System.out.println("2. Search for a student and their grade");
System.out.println("3. The class average");
System.out.println("4. The student with the highest grade");
System.out.println("5. The student with the lowest grade");
System.out.println("6. List of students that are failing");
System.out.println("7. Quit the program");
int options = input.nextInt();
switch(options) {
case 1:
letterGrade(options); break;
case 2:
searchStudent(); break;
case 3:
classAvg(options); break;
case 4:
markHighest(options); break;
case 5:
markLowest(options); break;
case 6:
markFailing(options); break;
case 7:
return;
default:
System.out.println("");
System.out.println("Please enter a valid option.");
System.out.println(""); break;
}
} while (!input.equals(7));
System.out.println("Program Terminated.");
}
public static void letterGrade(int numOfKids) {
System.out.println("Enter a grade: A, B, C, D, F");
letterGrade = input.next();
if (letterGrade.equalsIgnoreCase("a")) {
gradeMax = 100;
gradeMin = 80;
}
if (letterGrade.equalsIgnoreCase("b")) {
gradeMax = 79;
gradeMin = 70;
}
if (letterGrade.equalsIgnoreCase("c")) {
gradeMax = 69;
gradeMin = 60;
}
if (letterGrade.equalsIgnoreCase("d")) {
gradeMax = 59;
gradeMin = 50;
}
if (letterGrade.equalsIgnoreCase("f")) {
gradeMax = 49;
gradeMin = 0;
}
for (int i = 0; i < numOfKids; i++) {
if (studentGrade[i] <= gradeMax && studentGrade[i] >= gradeMin) {
System.out.println(studentName[i] + " has a " + letterGrade);
System.out.println(letterGrade + " is equivalent to " + gradeMin + " - " + gradeMax + "%");
}
}
}
public static void searchStudent() {
}
public static void classAvg(int numOfKids) {
int average = 0;
for (int i = 0; i < numOfKids; i++) {
average += studentGrade[i];
}
average = (average/numOfKids) * 100;
System.out.println("The average of the class will be " + average + "%");
}
public static void markHighest(int numOfKids) {
int highestNum = 0;
for (int i = 0; i < numOfKids; i++) {
if (studentGrade[i] > highestNum) {
highestNum = studentGrade[i];
}
}
System.out.println("The highest mark in the class is " + highestNum + "%");
}
public static void markLowest(int numOfKids) {
int lowestNum = 0;
for (int i = 0; i < numOfKids; i++) {
if (studentGrade[i] < lowestNum) {
lowestNum = studentGrade[i];
}
}
System.out.println("The highest mark in the class is " + lowestNum + "%");
}
public static void markFailing(int numOfKids) {
for (int i = 0; i < numOfKids; i++) {
if (studentGrade[i] < 50) {
System.out.println(studentName[i] + " is failing with a mark of " + studentGrade[i] + "%");
}
}
}
}
Looks like the argument passed to the classAvg() is not the numOfKids (or size of array) but the option selected by the user from the menu. Trying passing 'numOfKids' instead of passing 'options' as an argument to the function
case 3:
classAvg(options); break;
Better still use studentGrade.length instead of passing argument.
case 3:
classAvg(options); break;
You are passing in the options, but the method wants numOfKids. In this case options will always be 3.
Try passing in numOfKids instead.
Another problem I see is that both average and numOfKids are integers, which causes chopping remainders and rounding to 0 if the denominator is greater. Perhaps change from
average = (average/numOfKids) * 100;
to
average = ((double) average)/ numOfKids * 100;
I think it is better to create a class called Student, with properties name and grade. for more OOP design.
public class Student{
int[] grades;
String name;
public Student(int[] grade, String name){
this.grade = grade;
this.name = name;
}
public double getAverage(){
return (average/(double)numOfKids) * 100;
}
...
}
And average is of type int and numOfKids too, so the division is not gonna be precise. try this average = (average/(double)numOfKids) * 100;

Java 2D Seating Array for a Theater

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.

ATM assignment - why does balance reflect only most recent transactions?

I'm trying to make a ATM that can make deposit, withdrawal and show balance. But I have a problem with the program's balance it only shows the balance for the ten most recent transactions rather than all the transactions made.
I'm not allowed to use global variables,other methods and constants.
Here is how it should work
Earlier transactions:
=====================
1
2
3
4
5
6
7
8
9
10
=======================
Balance: 55 KR
Earlier transactions:
=====================
2
3
4
5
6
7
8
9
10
11
=======================
Balance: 66 KR
Code
import java.util.Scanner;
public class Bankomat
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
// Declarer variables
int[] trans = new int[10];
int amount = 0;
int balance = 0;
int sum = 0;
int theChoice = 1;
while(theChoice != 4)
{
theChoice= menu();
switch(theChoice)
{
case 1:
System.out.println("\nDu valde \"deposit\"");
System.out.print("\nState the value you want to take in: ");
sum = in.nextInt();
if(sum == 0)
{
System.out.print("\nYou have given are wrong value.\n");
}
else
{
amount = (int) + sum;
makeTransactions(trans,amount);
}
break;
case 2:
System.out.println("\nDu valde \"withdrawal\"");
System.out.print("\nState the value you want to take in: ");
sum = in.nextInt();
if(sum == 0)
{
System.out.print("\nDu har angett ett felaktigt belopp.\n");
}
else
{
amount = (int) - sum;
makeTransactions(trans,amount);
}
break;
case 3:
System.out.println("\nDu valde \"Balance\"");
showTransactions(trans,balance);
break;
case 4:
System.out.println("\nDu valde \"Quit\"");
break;
}
}
}
/**
* MENU
* #return val skickar tillbaka input värdet
*/
public static int menu()
{
Scanner in = new Scanner(System.in);
int choice = 0;
// Den här delen kommer att skriva ut menu
System.out.println("1. deposit");
System.out.println("2. withdrawal");
System.out.println("3. Balance");
System.out.println("4. Quit");
System.out.print("Your choice: ");
choice = in.nextInt();
return choice;
}
/**
* This method will sum up all the ten latest transaction and show the balance
* #param trans array that saves the latest transactions
* #param balance Int that sums up all the values
*/
public static void showTransactions(int[] trans, int balance )
{
System.out.println();
System.out.println("Tidigare transaktioner: ");
System.out.println("-------------------------------------------\n");
for(int i = 0; i < trans.length; i++)
{
if(trans[i] == 0)
{
System.out.print("");
}
else
{
System.out.print(trans[i] + "\n");
balance = balance + trans[i];
}
}
System.out.println("-------------------------------------------\n");
System.out.println("Saldo: " + balance + "KR" + "\n" );
}
/**
* This method saves the latest transaction
* #param trans array that saves the latest transactions
* #param amount int that saves the latest transaction
*/
public static void makeTransactions(int[] trans, int amount)
{
int position = findNr(trans);
if(position == -1)
{
moveTrans(trans);
trans[trans.length - 1] = amount;
}
else
{
trans[position] = amount;
}
}
/**
* This metod will look for a empty position
* #param trans array that saves the latest transactions
* #return position
*/
private static int findNr(int[] trans)
{
int position = -1;
for(int i = 0; i < trans.length; i++)
{
if (trans[i] == 0)
{
position = i;
break;
}
}
return position;
}
/**
* This method will move the transaction
* #param trans array that saves the latest transactions
*/
private static void moveTrans(int[] trans)
{
for(int i = 0; i < (trans.length - 1); i++)
{
trans[i] = trans[i + 1];
}
}
}
[EDITED] Complete solution:
public static void main(String[] args){
Scanner in = new Scanner(System.in);
// Declarer variables
int[] trans = new int[10];
int amount = 0;
int balance = 0;
int sum = 0;
int theChoice = 1;
while(theChoice != 4)
{
theChoice= menu();
switch(theChoice)
{
case 1:
System.out.println("\nDu valde \"deposit\"");
System.out.print("\nState the value you want to take in: ");
sum = in.nextInt();
if(sum == 0)
{
System.out.print("\nYou have given are wrong value.\n");
}
else
{
amount = (int) + sum;
balance += amount;
makeTransactions(trans,amount);
}
break;
case 2:
System.out.println("\nDu valde \"withdrawal\"");
System.out.print("\nState the value you want to take in: ");
sum = in.nextInt();
if(sum == 0)
{
System.out.print("\nDu har angett ett felaktigt belopp.\n");
}
else
{
amount = (int) - sum;
balance += amount;
makeTransactions(trans,amount);
}
break;
case 3:
System.out.println("\nDu valde \"Balance\"");
showTransactions(trans,balance);
break;
case 4:
System.out.println("\nDu valde \"Quit\"");
break;
}
}
}
/**
* MENU
* #return val skickar tillbaka input värdet
*/
public static int menu()
{
Scanner in = new Scanner(System.in);
int choice = 0;
// Den här delen kommer att skriva ut menu
System.out.println("1. deposit");
System.out.println("2. withdrawal");
System.out.println("3. Balance");
System.out.println("4. Quit");
System.out.print("Your choice: ");
choice = in.nextInt();
return choice;
}
/**
* This method will sum up all the ten latest transaction and show the balance
* #param trans array that saves the latest transactions
* #param balance Int that sums up all the values
*/
public static void showTransactions(int[] trans, int balance )
{
System.out.println();
System.out.println("Tidigare transaktioner: ");
System.out.println("-------------------------------------------\n");
for(int i = 0; i < trans.length; i++)
{
if(trans[i] == 0)
{
System.out.print("");
}
else
{
System.out.print(trans[i] + "\n");
}
}
System.out.println("-------------------------------------------\n");
System.out.println("Saldo: " + balance + "KR" + "\n" );
}
/**
* This method saves the latest transaction
* #param trans array that saves the latest transactions
* #param amount int that saves the latest transaction
*/
public static void makeTransactions(int[] trans, int amount)
{
int position = findNr(trans);
if(position == -1)
{
moveTrans(trans);
trans[trans.length - 1] = amount;
}
else
{
trans[position] = amount;
}
}
/**
* This metod will look for a empty position
* #param trans array that saves the latest transactions
* #return position
*/
private static int findNr(int[] trans)
{
int position = -1;
for(int i = 0; i < trans.length; i++)
{
if (trans[i] == 0)
{
position = i;
break;
}
}
return position;
}
/**
* This method will move the transaction
* #param trans array that saves the latest transactions
*/
private static void moveTrans(int[] trans)
{
for(int i = 0; i < (trans.length - 1); i++)
{
trans[i] = trans[i + 1];
}
}
The problem is because of how you initialized your int[] trans. You're only storing the first 10 transactions. You should use ArrayList instead, because it's dynamic.
ArrayList<Integer> trans = new ArrayList<Integer>, then to add new transactions to your array
It only shows the last 10 because you initialze your array to 10 indexes
int[] trans = new int[10];
Either make it bigger or use something different.
A great class to use in this case would be a vector. You don't need to initialize a size because it resizes itself dynamically.
Now, if you use a vector, but only want to print the last ten transactions, then surround your print statements in conditionals
if(i > trans.length - 10)
{
System.out.print(trans[i] + "\n");
}
The reson for this is in your showTransactions() not only are you printing the transactions, you are also adding them, computing your balance. We want to compute your balance with all your transactions (thus we need to change your array to a vector or other class with dynamic resizing) while also only printing what you need (thus the if statement)

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.

Java Multiplication Table how to prompt user for rows etc

I need to prompt the user to enter a number 1 through 5. This is the size of the multiplication table. If a user puts in a number greater than 5 or a negative number, then program tells them they have input an invalid number and prompts them again, and if the user enters 0, then stop the execution of the program. Can someone help me write this part?
What I have so far:
// Beginning of class MultiplicationTable
public class MultiplicationTable {
// Beginning of method main
public static void main(String[] args) {
/* Declare and initialize primitive variables */
int result;
/* Header */
// First, print some space
System.out.print(" ");
// Then, print numbers from 1 to 5 across the top
for (int j = 1; j <= 5; j++) {
System.out.print(" " + j);
}
System.out.println();
/* Separator */
// Print a dashed line
for (int j = 1; j < 50; j++) {
System.out.print("-");
}
System.out.println();
/* Values */
// Outer loop: multipliers
for (int outer = 1; outer <= 5; outer++) {
System.out.print(outer + " | ");
// Inner loop: values
for (int inner = 1; inner <= 5; inner++) {
// Calculate the value
result = outer * inner;
// Format the output
if (result < 10) {
// Here, we need an extra space if the result is 1 digit
System.out.print(" " + result);
}
else {
System.out.print(" " + result);
}
} // End for inner
System.out.println();
} // End for outer
} // End of method main
} // End of class MultiplicationTable
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
int num;
while(true)
{
try
{
System.out.print("Enter a number from 1 to 5: ");
num = Integer.parseInt(input.readLine());
if(num >= 1 && num <= 5)
break;
else
System.out.println("Number must be between 1 and 5");
}
catch(IOException e)
{
e.printStackTrace();
}
catch(NumberFormatException e)
{
System.out.println("Not an integer!");
}
}
This will keep prompting for input until they enter an integer between 1 and 5. That integer will be saved in "num".

Categories

Resources