Question

In: Computer Science

Below are three methods: checkValidInput, getCoordinates and play. Looking at checkValidInput, I feel it is very...

Below are three methods: checkValidInput, getCoordinates and play. Looking at checkValidInput, I feel it is very longwinded and would like to modify by using a try/catch block for user input. How is this occomplised? Would I be able to get rid of checkValidInput method with a try/catch? Any code to help me out would be great.

public boolean checkValidInput(String input){
    ArrayList<String> numList = new ArrayList<String>();
    for (int i=0;i<10;i++){
        numList.add(""+i);
    }
    String[] coordinates = input.split(" ");
    //returns false if there are not 2 strings
    if (coordinates.length!=2){
        return false;
    }
    //returns false if first is String is not in between A and J
    if(coordinates[0].charAt(0)<'A' || coordinates[0].charAt(0)>'J')
        return false;
    //returns false if the second string is not a single digit number
    for (String str: coordinates[1]){
        if (numList.contains(str)==false){
            return false;
        }
    }
    //returns false if the coordinates have already been shot at
    int row = Integer.parseInt(coordinates[0]);
    int column = Integer.parseInt(coordinates[1]);
    if (this.availableSpot[row][column]==false){
        return false;
    }

    return true;
}
public int[] getCoordinates(String input)
{
    int[] coordinates = new int[2];
    String[] strList = input.split(" ");
    int row = (int) strList[0].charAt(0) - 65;
    int column = Integer.parseInt(strList[1]);
    coordinates[0] = row;
    coordinates[1] = column;
    return coordinates;
}
public void play()
{
    print(101);
    print(1);
    ocean.randomShipDeployment();
    boolean isGameOver = ocean.isGameOver();
    sc = new Scanner(System.in);

    //printOcean the ocean and start the game
    ocean.printOcean();
    print(3);
    while (!isGameOver)
    {
        print(2);
        String input = sc.nextLine();

        //check if input is valid
        while (!checkValidInput(input))
        {
            print(99);
            input = sc.nextLine();
        }

        //get coordinates and fire
        int[] coordinates = getCoordinates(input);
        int row = coordinates[0];
        int column = coordinates[1];
        ocean.shotFiredAtLocation(row, column);
        availableSpot[row][column] = false;
        isGameOver = ocean.isGameOver();
        ocean.printOcean();
        print(3);
        print(100);
    }
    //printOcean info saying you win
    print(4);
    print(5);
}

Solutions

Expert Solution

One of the way to use try catch in given example is to use User defined Exception

following class can be added for user defined exception :

class ValidInputException extends Exception{
int a;
ValidInputException(int b) {
a=b;
}
public String toString(){
if(a==1){
return ("Exception "+a+" : Input not contains 2 strings") ;
}
else if(a==2){
return ("Exception "+a+" : first String in Input is not in between A and J") ;
}
else if(a==3){
return ("Exception "+a+" : second string is not a single digit number ") ;
}
else if(a==4){
return ("Exception "+a+" : The coordinates have already been shot at ") ;
}
return ("Exception Number = "+a) ;
}
}

Your checkvalidIput(String input) will change accordingly ->

public boolean checkValidInput(String input){
  
try{
ArrayList<String> numList = new ArrayList<String>();
for (int i=0;i<10;i++){
numList.add(""+i);
}
String[] coordinates = input.split(" ");
//returns false if there are not 2 strings
if (coordinates.length!=2){
//return false;
throw new ValidInputException(1);
}
//returns false if first is String is not in between A and J
if(coordinates[0].charAt(0)<'A' || coordinates[0].charAt(0)>'J')
//return false;
throw new ValidInputException(2);
//returns false if the second string is not a single digit number
/*
for (String str: coordinates[1]){
if (numList.contains(str)==false){
return false;
}
}
*/
String str= coordinates[1];
if(str.length()!=1 || numList.contains(str)==false){
throw new ValidInputException(3);// returns false if the second string is not a single digit number
//return false;
}
  
//returns false if the coordinates have already been shot at
int row = Integer.parseInt(coordinates[0]);
int column = Integer.parseInt(coordinates[1]);
if (this.availableSpot[row][column]==false){
//return false;
throw new ValidInputException(4);
}


}
catch(ValidInputException e){
System.out.println(e);
}

return true;
}


Related Solutions

After take a cup of the coffee i feel my head weight is too high very...
After take a cup of the coffee i feel my head weight is too high very uncomfortable feeling. hyper sensitivity. head top is not feel when touch. what reason? i am magrine patient. caffine is bad for magrine. but i use coffee when i am 10 year old now 22.
How do i solve the question below: You are looking at an investment that will pay...
How do i solve the question below: You are looking at an investment that will pay you $27,250 in year 2, $44,098 in year 4 and $49,414 in year 6. If your required return is 8.49%, what is the most you should pay for the investment? (In other words, how much is the project worth today?) 2. If you have $485 today and you think you can earn an interest rate of 6% per year, how many years until you...
The question below is very long and I am not sure how to answer some of...
The question below is very long and I am not sure how to answer some of the questions. How much energy is needed for normal breathing? and How might this change with lung disease? how the ingredients in tobacco smoke damage/impair the respiratory system? What brain region controls respiration? What gas do the respiratory centers of the brain detect? How does this affect the respiration rate??
Looking for assistance on these three quick questions as I can't seem to figure them out....
Looking for assistance on these three quick questions as I can't seem to figure them out. Thanks in advance for your help! 1. Which of the following would decrease the depth of breathing? A. Increased arterial PCO2 B. Exercising C. Increased action potential frequency in neurons from the ventral respiratory group D. Acidic plasma pH E. Decreased action potential frequency in neurons from the dorsal respiratory group F. Overactivation of the respiratory center in the medulla 2. Which of the...
I worked on this my self but I am not sure about it and I feel...
I worked on this my self but I am not sure about it and I feel like I get confuse in explaining some of them, I want to capare and contrast the different types of membrane transport processes.( including differences and similarities) simple diffusion facilitated difusion osmosis primaryactive transport secendary active transport vesicular transport The comparison and similarities should be about each of these topics. 1.direction of transport 2.energy requirement 3.protein requirement 4.types of protein if applicable 5. example of...
Looking at the below article, answer the following: What flaws in Basel I did Basel II...
Looking at the below article, answer the following: What flaws in Basel I did Basel II attempt to remedy and what provisions did it make for doing so? What short-comings in bank capital regulation remain? The Rise of Basel II Soon, a variety of inherent flaws in Basel I’s treatment of capital became apparent. First, the relationship between assets’ actual revealed default risk and their risk weights proved to be less reliable than had been thought. For instance, all bonds...
The Young household is looking at buying a house. The three houses they are looking at...
The Young household is looking at buying a house. The three houses they are looking at cost the following: $160,000, $190,000 and $210,000. They can pay up to $900 in monthly mortgage payments. They currently have $18,000 set aside for a down payment. Similarly to the Tremblay’s bank, the Youngs’ bank will add $40 to each mortgage payment if they put less than 20% down and an additional fee of $30 more to each payment if they put less than...
Employees can be very satisfied when it comes to compensation when they feel they are respected...
Employees can be very satisfied when it comes to compensation when they feel they are respected for their performance by offering a higher salary. You provided great research in your information and have excellent information to support your thoughts. When you were researching your information, do you feel there is a difference better upper level employees and line managers, and line employees when it comes to motivating employees with compensation? How does compensation affect the attitude of employees in the...
Out of the numerous methods to evaluate a small company, i need to illustrate three through...
Out of the numerous methods to evaluate a small company, i need to illustrate three through excel (please explain in detail how this would work or how it should be laid out if possible thank you!) ..can upload an excel file to follow if that works (sorry about the error from earlier post)
Who are three I/O theorists or psychologists and describe the potential impact of their research methods
Who are three I/O theorists or psychologists and describe the potential impact of their research methods
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT