Question

Debug and fix the Java console application that uses 2 dimensional arrays but the application does...

Debug and fix the Java console application that uses 2 dimensional arrays but the application does not compile nor execute. Student enters only integers to select courses for registration from a menu. No data type validation of the user menu selection is checked or required. The program terminates only when the student closes it. No registration of other courses not displayed by the program . No registration more than once for the same course. No registration for more than 9 credit hours (e.g. no more than 3 courses). This program has 4 errors/bugs. Use these to test the outcome IT1006 IT4079 IT2230 Successful completion of this assignment will display a valid message or an invalid message, with reason, for the selected course code. In addition, the application should display and update current list of registered courses. Here is the code I have so far: package registerforcourse; import java.util.Scanner; public class RegisterForCourse { public static void main(String[] args) { // TODO code application logic here System.out.println("Register for classes"); Scanner input = new Scanner(System.in); // courses 2d array hold course code and their credit hours String[][] courses = { {"IT1006", "IT4782", "IT4789", "IT4079", "IT2230", "IT3345", "IT2249"}, {"6", "3", "3", "6", "3", "3", "6"} }; // validChoices 2d array holds valid number choices (as strings) selected by user // and their corresponding courses //e.g String[][] choices = { {"5", "IT2230"}, {"1", "IT1006"}, {"6", "IT3345"} }; String[][] validChoices = { {"", ""}, {"", ""}, {"", ""} }; int choice; int totalCredit = 0; String yesOrNo = ""; do { choice = getChoice(courses, input); switch (ValidateChoice(choice, validChoices, totalCredit, courses)) { case -1: System.out.println("**Invalid** - Your selection of " + choice + " is not a recognized course."); break; case -2: System.out.println("**Invalid** - You have already registerd for this " + courses[0][choice-1] + " course."); break; case -3: System.out.println("**Invalid** - You can not register for more than 9 credit hours."); break; case 0: System.out.println("Registration Confirmed for course " + courses[0][choice-1] ); totalCredit += Integer.parseInt(courses[1][choice-1]); if (validChoices[0][0].equals("")) { validChoices[0][0] = Integer.toString(choice); validChoices[0] = courses[0][choice-1]; } else if (validChoices[1][0].equals("")) { validChoices[1][0] = Integer.toString(choice); validChoices[1][1] = courses[0][choice-1]; } else if (validChoices[2][0].equals("")) { validChoices[2][0] = Integer.toString(choice); validChoices[2][1] = courses[0][choice-1]; } break; } WriteCurrentRegistration(validChoices, totalCredit); System.out.print("\nDo you want to try again? (Y|N)? : "); yesOrNo = input.next().toUpperCase(); } while (yesOrNo.equals("Y")); System.out.println("Thank you for registering with us"); } //This method prints out the selection menu to the user in the form of //[selection number]Course Code (Course Credit Hours) //from the courses array one per line //and then prompts the use to make a number selection public static int getChoice(String[] courses, Scanner input) { System.out.println("Please type the number inside the [] to register for a course"); System.out.println("The number inside the () is the credit hours for the course"); for(int i = 0; i < courses[0].length; i++ ) System.out.println("[" + (i+1) + "]" + courses[0][i] + "(" + courses[1][i] + ")"); System.out.print("Enter your choice : "); return (input.nextInt()); } //This method validates the user menu selection //against the given registration business rules //it returns the following code based on the validation result // -1 = invalid, unrecognized menu selection // -2 = invalid, alredy registered for the course // -3 = invalid, No more than 9 credit hours allowed // 0 = menu selection is valid public static int ValidateChoice(int choice, String[][] validChoices, int totalCredit, String[][] courses) { String choiceAsString = Integer.toString(choice); if (choice < 1 || choice > 7) return -1; else if (choiceAsString.equals(validChoices[0][0]) || choiceAsString.equals(validChoices[]) || choiceAsString.equals(validChoices[2][0])) return -2; else if ( totalCredit + Integer.parseInt(courses[1][choice-1]) > 9) return -3; return 0; } //This method prints the current list of registered courses thus far //from the courses array separated by , and enclosed inside { } //It also prints the total credit registered for thus far public static void WriteCurrentRegistration(String[][] validChoices, int totalCredit) { if (validChoices[0][0].equals("")) System.out.println("Current course registration: { none } " ); else if (validChoices[1][0].equals("")) System.out.println("Current course registration: { " + validChoices[0][i] + " }" ); else if (validChoices[2][0].equals("")) System.out.println("Current course registration: { " + validChoices[0][1] + ", " + validChoices[1][1] + " }"); else System.out.println("Current course registration: { " + validChoices[0][1] + ", " + validChoices[1][1] + ", " + validChoices[2][1] + " }"); System.out.println("Current registration total credit = " + totalCredit); } } Expert Answer

0 0
Add a comment Improve this question Transcribed image text
Answer #1

I've gone through the source code and first tried to reformat it.

Then I started to find the bugs to resole them.

It's somewhat hard to tell the line numbers as it gets changed considering new lines and may change while posting in browser so I am writing the line of code that has the error.

1. choice = getChoice(courses, input)

It is in main() method.

2.   for (int i = 0; i < courses[0].length; i++) {
3. System.out.println("[" + (i + 1) + "]" + courses[0][i] + "(" + courses[1][i] + ")")

These two lines are in getChoice() method.

The cause for all the 3 is first bug.

The header of method getChoice() is defined as   public static int getChoice(String[ ] courses, Scanner input) where courses is written a single dimension array but actually in main() it is 2-D array. And as it is 2D array, one can write statement like this courses[0].length which is valid otherwise courses[0] would be an array element which does not have a length property. The next line is the code referring to 2-D array and as it was defined 1-D in getChoice(), these lines are giving errors

So, when I changed the method header and wrote courses as a 2-dimension array, all the 3 lines were not having any error now.

Second bug/error is in main() in the line: validChoices[0] = courses[0][choice - 1];

'validChoices' is a 2-D array but its only first dimension is mentioned second is not.

If you see the code written along with this line, you can say that if validChoices[0][0] is empty, then the course name should be addedd to validChoices[0][1]. So, adding [1] will solve this error.

Next error is in the following line in the method ValidateChoice() :

else if (choiceAsString.equals(validChoices[0][0]) || choiceAsString.equals(validChoices[ ]) || choiceAsString.equals(validChoices[2][0])) {

Here, if you see, the second condition written is choiceAsString.equals(validChoices[ ])

In other two conditions in the same else if, choiceAsString is compared with validChoices[0][0] and validChoices[2][0] but in the second part. there's no index specified for validChoices [ ] [ ].

Here it should be validChoices[1][0] as other two course names stored at index [0] [0] and [2] [0] are compared in the same line, validChoices[1] [0] is remaining.

The last error is in the following line in the method WriteCurrentRegistration()..

System.out.println("Current course registration: { " + validChoices[0][i] + " }")

Here, validChoices[0][i] is written but variable 'i' is not defined inside WriteCurrentRegistration() method.

If you see the other statements in the same method, in the first value printed inside all other println() is validChoices[0][1].

So, here also it should be the validChoices[0][1] instead of validChoices[ 0 ][ i ].

So when we fix the 4 errors we'll get the modified source code as follows.. In the code, I've make the text BOLD where the changes are done.

Modified Source Code:

package registerforcourse;

import java.util.Scanner;

public class ResgisterForCourse {

public static void main(String[ ] args) {
System.out.println("Register for classes");
Scanner input = new Scanner(System.in);
String[ ][ ] courses = {{"IT1006", "IT4782", "IT4789", "IT4079", "IT2230", "IT3345", "IT2249"}, {"6", "3", "3", "6", "3", "3", "6"}};
String[ ][ ] validChoices = {{"", ""}, {"", ""}, {"", ""}};
int choice;
int totalCredit = 0;
String yesOrNo = "";
do {
choice = getChoice(courses, input);
switch (ValidateChoice(choice, validChoices, totalCredit, courses)) {
case -1:
System.out.println("**Invalid** - Your selection of " + choice + " is not a recognized course.");
break;
case -2:
System.out.println("**Invalid** - You have already registerd for this " + courses[0][choice - 1] + " course.");
break;
case -3:
System.out.println("**Invalid** - You can not register for more than 9 credit hours.");
break;
case 0:
System.out.println("Registration Confirmed for course " + courses[0][choice - 1]);
totalCredit += Integer.parseInt(courses[1][choice - 1]);
if (validChoices[0][0].equals("")) {
validChoices[0][0] = Integer.toString(choice);
validChoices[0][1] = courses[0][choice - 1]; // to solve bug 2
} else if (validChoices[1][0].equals("")) {
validChoices[1][0] = Integer.toString(choice);
validChoices[1][1] = courses[0][choice - 1];
} else if (validChoices[2][0].equals("")) {
validChoices[2][0] = Integer.toString(choice);
validChoices[2][1] = courses[0][choice - 1];
}
break;
}
WriteCurrentRegistration(validChoices, totalCredit);
System.out.print("\nDo you want to try again? (Y|N)? : ");
yesOrNo = input.next().toUpperCase();
} while (yesOrNo.equals("Y"));
System.out.println("Thank you for registering with us");
}

public static int getChoice(String[ ][ ] courses, Scanner input) { // to solve first bug
System.out.println("Please type the number inside the [ ] to register for a course");
System.out.println("The number inside the () is the credit hours for the course");
for (int i = 0; i < courses[0].length; i++) {
System.out.println("[" + (i + 1) + "]" + courses[0][i] + "(" + courses[1][i] + ")");
}
System.out.print("Enter your choice : ");
return (input.nextInt());
}

public static int ValidateChoice(int choice, String[ ][ ] validChoices, int totalCredit, String[ ][ ] courses) {
String choiceAsString = Integer.toString(choice);
if (choice < 1 || choice > 7) {
return -1;
} else if (choiceAsString.equals(validChoices[0][0]) || choiceAsString.equals(validChoices[1][0]) || choiceAsString.equals(validChoices[2][0])) { // to solve bug 3
return -2;
} else if (totalCredit + Integer.parseInt(courses[1][choice - 1]) > 9) {
return -3;
}
return 0;
}

public static void WriteCurrentRegistration(String[ ][ ] validChoices, int totalCredit) {
if (validChoices[0][0].equals("")) {
System.out.println("Current course registration: { none } ");
} else if (validChoices[1][0].equals("")) {
System.out.println("Current course registration: { " + validChoices[0][1] + " }"); // to solve bug 4
} else if (validChoices[2][0].equals("")) {
System.out.println("Current course registration: { " + validChoices[0][1] + ", " + validChoices[1][1] + " }");
} else {
System.out.println("Current course registration: { " + validChoices[0][1] + ", " + validChoices[1][1] + ", " + validChoices[2][1] + " }");
}

System.out.println("Current registration total credit = " + totalCredit);
}
}

Output:

run: Register for classes Please type the number inside the [1 to register for a course The number inside the ) is the credit


Do you want to try again? (YIN)? y Please type the number inside the [] to register for a course The number inside the () is

So when I executed this modified code, it had no error and it executed successfully as per the output above.

See it is allowing to register for a course and maximum allowed hrs = 9 so it refuses to add 6 to current 6 while entering a course second time, but in third time it allows as total hours become 6 + 3 = 9 which is acceptable.

So, this is how to solve the bugs in the code. The concepts and the code is already designed and these were the things which were preventing the code to be executed. Now they are solved.

Go through the process of identifying the lines where the errors were and why they were an error and how they were solved.

Do comment if there's any query. I will address it for sure.

Thank you. :)

Add a comment
Know the answer?
Add Answer to:
Debug and fix the Java console application that uses 2 dimensional arrays but the application does...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • kindly Explain, briefly IN PLAIN ENGLISH, how this exercise was completed and the algorithm you used...

    kindly Explain, briefly IN PLAIN ENGLISH, how this exercise was completed and the algorithm you used /* * 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. */ // package u10a1_ooconsoleregisterforcourse; import java.util.Scanner; /** * * @author omora */ public class U10A1_OOConsoleRegisterForCourse { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO...

  • Hi I need help with a java program that I need to create a Airline Reservation...

    Hi I need help with a java program that I need to create a Airline Reservation System I already finish it but it doesnt work can someone please help me I would be delighted it doesnt show the available seats when running the program and I need it to run until someone says no for booking a seat and if they want to cancel a seat it should ask the user to cancel a seat or continue booking also it...

  • Writing 3 Java Classes for Student registration /** * A class which maintains basic information about...

    Writing 3 Java Classes for Student registration /** * A class which maintains basic information about an academic course. */ public class Course {    /** * Attributes. */ private String code; private String title; private String dept; // name of department offering the course private int credits; /** * Constructor. */ public Course(String code, String title, int credits) { // TODO : initialize instance variables, use the static method defined in // Registrar to initialize the dept name variable...

  • Please modify the following code to NOT have "TicTacToe extends Board" (I don't want any extending)....

    Please modify the following code to NOT have "TicTacToe extends Board" (I don't want any extending). Please ensure the resulting code completes EACH part of the following prompt: "Your task is to create a game of Tic-Tac-Toe using a 2-Dimensional String array as the game board. Start by creating a Board class that holds the array. The constructor should use a traditional for-loop to fill the array with "blank" Strings (eg. "-"). You may want to include other instance data......

  • In Java Code Needed is Below the Question Using Program 3: Encapsulating Dogs, modify this program...

    In Java Code Needed is Below the Question Using Program 3: Encapsulating Dogs, modify this program to create a database of dogs of your own. You will also include File I/O with this program. You will create 3 classes for this assignment. The first class: Create a Class representing the information that is associated with one item (one dog) of your database. Name this class Dog. Using Lab 3, this will include the information in regard to one dog. The...

  • In this assessment, you will design and code a Java console application that validates the data...

    In this assessment, you will design and code a Java console application that validates the data entry of a course code (like IT4782) and report back if the course code is valid or not valid. The application uses the Java char and String data types to implement the validation. You can use either the Toolwire environment or your local Java development environment to complete this assignment. The requirements of this application are as follows: The application is to read a...

  • Provide comments for this code explaining what each line of code does import java.util.*; public class...

    Provide comments for this code explaining what each line of code does import java.util.*; public class Chpt8_Project {    public static void main(String[] args)       {        Scanner sc=new Scanner(System.in);        int [][]courses=new int [10][2];        for(int i=0;i<10;i++)        {            while(true)            {                System.out.print("Enter classes and graduation year for student "+(i+1)+":");                courses[i][0]=sc.nextInt();                courses[i][1]=sc.nextInt();                if(courses[i][0]>=1...

  • Why does my program generate [] when viewing all guests names? ----------------------------------------------- import java.util.*; public class...

    Why does my program generate [] when viewing all guests names? ----------------------------------------------- import java.util.*; public class Delete extends Info { String name; int Id; int del; public Delete() { } public void display() { Scanner key = new Scanner(System.in); System.out.println("Input Customer Name: "); name = key.nextLine(); System.out.println("Enter ID Number: "); Id = key.nextInt(); System.out.println("Would you like to Delete? Enter 1 for yes or 2 for no. "); del = key.nextInt(); if (del == 1) { int flag = 0; //learned...

  • Please fix my code so I can get this output: Enter the first 12-digit of an...

    Please fix my code so I can get this output: Enter the first 12-digit of an ISBN number as a string: 978013213080 The ISBN number is 9780132130806 This was my output: import java.util.Scanner; public class Isbn { private static int getChecksum(String s) { // Calculate checksum int sum = 0; for (int i = 0; i < s.length(); i++) if (i % 2 == 0) sum += (s.charAt(i) - '0') * 3; else sum += s.charAt(i) - '0'; return 10...

  • JAVA // TO DO: add your implementation and JavaDoc public class SmartArray<T>{    private static final...

    JAVA // TO DO: add your implementation and JavaDoc public class SmartArray<T>{    private static final int DEFAULT_CAPACITY = 2;   //default initial capacity / minimum capacity    private T[] data;   //underlying array    // ADD MORE PRIVATE MEMBERS HERE IF NEEDED!       @SuppressWarnings("unchecked")    public SmartArray(){        //constructor        //initial capacity of the array should be DEFAULT_CAPACITY    }    @SuppressWarnings("unchecked")    public SmartArray(int initialCapacity){        // constructor        // set the initial capacity of...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT