Question about try, catch
How do I make the code go back so that once user type more than 20
characters in the string, it will print a message and then continue to
process more strings?
Here is the code:
//StringTooLongExceptionDriver
import java.util.Scanner;
import java.io.*;
public class StringTooLongExceptionDriver
{
//
// The main method prompts and reads strings. If the string has more
// than 20 characters, it throws a StringTooLongException exception.
//
public static void main(String[] args){
//System.out.println("Enter a string: ");
String strInput = "";
int newStringCounter;
int arrayCounter=0;
char[] myCharArray = new char[20];
InputStreamReader myRead = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(myRead);
try{
while (!(strInput.equals("DONE"))){
System.out.println("enter your string: ");
int x = 0;
strInput = in.readLine();
newStringCounter = strInput.length();
if (!(strInput.equals("DONE"))){
while (newStringCounter > 0){
myCharArray[arrayCounter] = strInput.charAt(x);
newStringCounter--;
System.out.print("the last char at array is " +
myCharArray[arrayCounter]);
System.out.println(" and array counter is " + arrayCounter);
x++;
arrayCounter++;
}
}
}
if (strInput.equals("DONE")){
System.out.print("you have enterd: ");
for (int i=0; i<=arrayCounter-1; i++){
System.out.print(myCharArray[i]);
}
System.out.println("");
System.out.println("End of the string you have enterd!");
}
}
catch(Exception e){
StringTooLongException error = new StringTooLongException("Total
string character now is larger than 20 characters");
error.EndHere();
}
}
}
class StringTooLongException
{
String statement = "";
public StringTooLongException(String myError){
statement = myError;
System.out.println(statement);
}
public void EndHere(){
System.out.println("please try again");
System.exit(0);
}
}