I am need some quick help with finishing an assignment, In short I completed an assignment that required me to make a program that allowed the user to pop(), push() and top() an array.
I did it but my tutor said that the code layout wrong as I had System.out.println statements in the stack class and these should be in the main menu app, and the stack class should only called the methods that it inherits from the array class.
Fair enough I thought and I amended the code but I cannot get the push() method to work correctly now :/
I know that I need to use the Genio.getInteger method in the menu app push()method.
Can anyone help?
Stack Class:
public class Stack extends Array
{
private int x;
public Stack()
{
super();// initialise instance variables
x = 0;
}
public Stack(int newsize)
{
super(newsize);
System.out.println("Stack Created!");
}
/**
* #push user is asked to enter value at keyboard which is then added to the top of the stack
*
*/
public boolean push(int item)
{
return add(item);
}
/**
* #pop removes the current value staored at the top of the stack
*
*/
public int pop()
{
deleteLast();
return getItemback();
}
/**
* #top displays the current value stored at the top of the stack
*
*/
public int top()
{
displayLast();
return getItemback();
}
}
Menu app:
public static void main()
{
int option;
int item;
Stack s = new Stack();
String []menuitems = {"1 - Display Stack","2 - Pop Stack", "3 - Push Onto Stack","4 - Top Of Stack","5 - Quit Program"};
Menu m = new Menu(menuitems,5);
s.add(12);s.add(2);s.add(1);s.add(13);s.add(24);
do
{
clrscr();
option = m.showMenu();
if ( option == 1 )
{
s.display();
pressKey();
}
if ( option == 2 )
{
if (!s.isEmpty())
System.out.println ("Number Popped: ");
else
System.out.println ("The Stack Is Empty! ");
pressKey();
}
// THIS IS THE PART I CANNOT GET TO WORK!! NOT SURE WHERE/HOW TO CALL PUSH
// METHOD?
if ( option == 3 )
{
item = Genio.getInteger();
if (!s.isFull())
System.out.println("Please Enter Number To be Pushed(" + item + ")");
else
System.out.println("Stack Overflow! ");
pressKey();
}
if ( option == 4 )
{
if (!s.isEmpty())
s.top();
else
System.out.println ("The Stack Is Empty! ");
pressKey();
}
}
while ( option != 5 );
System.out.println("\nDone! \n(You Can Now Exit The Program)\n");
}
/**
* #clrscr removes all text from the screen
*
*/
public static void clrscr()
{
for ( int i=1;i<=50;i++)
System.out.println();
}
/**
* #pressKey requires the user to press return to continue
*
*/
public static void pressKey()
{
String s;
System.out.print("\nPress return to continue : ");
s = Genio.getString();
}
}
EDIT: Genio class if relevant?:
public class Genio
{
/**
* Constructor for objects of class genio, but nothing needing constructed!
*/
public Genio()
{
}
/**
* getStr() is a private method which safely returns a string for use
* by the public methods getString() and getCharacter() in the class.
*
* #return String for further processing withing the class
*/
private static String getStr()
{
String inputLine = "";
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
try
{
inputLine = reader.readLine();
}
catch(Exception exc)
{
System.out.println ("There was an error during reading: "
+ exc.getMessage());
}
return inputLine;
}
/**
* getInteger() returns an integer value. Exception handling is used to trap
* invalid data - including floating point numbers, non-numeric characters
* and no data. In the event of an exception, the user is prompted to enter
* the correct data in the correct format.
*
* #return validated int value
*/
public static int getInteger()
{
int temp=0;
boolean OK = false;
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
do
{
try
{
temp = Integer.parseInt(keyboard.readLine());
OK = true;
}
catch (Exception eRef)
{
if (eRef instanceof NumberFormatException)
{
System.out.print("Integer value needed: ");
}
else
{
System.out.println("Please report this error: "+eRef.toString());
}
}
} while(OK == false);
return(temp);
}
/**
* getFloat() returns a floating point value. Exception handling is used to trap
* invalid data - including non-numeric characters and no data.
* In the event of an exception (normally no data or alpha), the user is prompted to enter
* data in the correct format
*
* #return validated float value
*/
public static float getFloat()
{
float temp=0;
boolean OK = false;
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
do
{
try
{
temp = Float.parseFloat(keyboard.readLine());
OK = true;
}
catch (Exception eRef)
{
if (eRef instanceof NumberFormatException)
{
System.out.print("Number needed: ");
}
else
{
System.out.println("Please report this error: "+eRef.toString());
}
}
} while(OK == false);
return(temp);
}
/**
* getDouble() returns a double precision floating point value.
* Exception handling is used to trap invalid data - including non-numeric
* characters and no data.
* In the event of an exception, the user is prompted to enter
* data in the correct format
*
* #return validated double precision value
*/
public static double getDouble()
{
double temp=0;
boolean OK = false;
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
do
{
try
{
temp = Double.parseDouble(keyboard.readLine());
OK = true;
}
catch (Exception eRef)
{
if (eRef instanceof NumberFormatException)
{
System.out.print("Number needed: ");
}
else
{
System.out.println("Please report this error: "+eRef.toString());
}
}
} while(OK == false);
return(temp);
}
/**
* getCharacter() returns a character from the keyboard. It does this by
* reading a string then taking the first character read. Subsequent characters
* are discarded without raising an exception.
* The method checks to ensure a character has been entered, and prompts
* if it has not.
*
* #return validated character value
*/
public static char getCharacter()
{
String tempStr="";
char temp=' ';
boolean OK = false;
do
{
try
{
tempStr = getStr();
temp = tempStr.charAt(0);
OK = true;
}
catch (Exception eRef)
{
if (eRef instanceof StringIndexOutOfBoundsException)
{
// means nothing was entered so prompt ...
System.out.print("Enter a character: ");
}
else
{
System.out.println("Please report this error: "+eRef.toString());
}
}
} while(OK == false);
return(temp);
}
/**
* getString() returns a String entered at the keyboard.
* #return String value
*/
public static String getString()
{
String temp="";
try
{
temp = getStr();
}
catch (Exception eRef)
{
System.out.println("Please report this error: "+eRef.toString());
}
return(temp);
}
}
Not sure if I understood your question correctly, but s.push isn't being called? (s.pop isn't either?)
If you'll replace
if (!s.isFull())
with
if (!s.isFull() && s.push(item))
some work will get done?
If you want it only to be a prompt, use curly brackets (use them anyway, it'll save you from horrid bugs one day). Something like this.
if (!s.isFull()) {
System.out.println("enter a number to add");
Scanner sc = new Scanner(System.in);
s.push(sc.nextInt());
}
Related
So I am working with a program that is supposed to incorporate try-catch blocks for exception handling. What I can't figure out is how to write a simple if statement for checking input from the user via Scanner to make sure it is a double and not a letter or a character so that if it is the program will catch it, display the error message, and tell the user to re-enter another value until a suitable input is entered. What I am looking for is a simple if(_width equals a letter/character) then return false along with an error message to go along with my already present if statement that checks whether the input is greater than zero.
my current code is below:
public class Rectangle {
//two double data fields width and height, default values are 1 for both.
private double width = 1;
private double height = 1;
private String errorMessage = "";
//no-arg constructor creates default rectangle
public Rectangle() {
}
//fpzc, called by another program with a statement like Rectangle rec = new Rectangle(#, #);
public Rectangle (double _width, double _height) throws Exception {
setWidth(_width);
setHeight(_height);
}
//get functions
public double getArea(){
return (width * height);
}
public double getPerimeter() {
return (2*(width + height));
}
public String getErrorMessage() {
return errorMessage;
}
//set functions
public void setWidth(double _width) throws Exception {
if( !isValidWidth(_width)){
Exception e = new Exception(errorMessage);
throw e;
//System.out.println(errorMessage);
//return false;
}
width = _width;
}
public void setHeight(double _height) throws Exception {
if ( !isValidHeight(_height)){
Exception e = new Exception(errorMessage);
throw e;
//System.out.println(errorMessage);
//return false;
}
height = _height;
}
//isValid methods
public boolean isValidWidth(double _width) {
if(_width > 0){
return true;
}
else {
errorMessage = "Invalid value for width, must be greater than zero";
return false;
}
if ()
}
public boolean isValidHeight(double _height) {
if(_height > 0){
return true;
}
else {
errorMessage = "Invalid value for height, must be greater than zero";
return false;
}
}
}
My class is being called by another test program that i have written correctly. Any help is appreciated! Thank you.
maybe something like:
String errorMessage = "error";
Scanner in = new Scanner(System.in);
String str = in.nextLine();
try {
Double.parseDouble(str);
}
catch( Exception e ){
System.out.println(errorMessage);
}
or iterate through the input and check if each character is digit:
String errorMessage = "error";
Scanner in = new Scanner(System.in);
String str = in.nextLine();
for(int i=0;i<str.length();i++){
char token = str.charAt(i);
if(!Character.isDigit(token) && token!='.' ) {
System.out.println(token + " doesnt work");
break;
}
}
On declaring your scanner you could also:
double num;
String errorMessage = "error";
while(true) {
Scanner in = new Scanner(System.in);
if (in.hasNextDouble()) {
num = in.nextDouble();
System.out.println(num);
break;
}
else System.out.println(errorMessage);
}
Maybe this code helps you:
double Input=0;
while(!(Input > 0)){{
System.out.println("Enter Valid Number");
Input = new Scanner(System.in).nextDouble();
}
I am trying to create a program that accepts as many Social Security Numbers as the user wants to input. The only restriction is that the numbers must follow the format XXX-XX-XXXX and not accept duplicated entries. This is what I have so far:
Subclass 2
package SSNServerStorageExpanded;
class SSNArray{
final String[] ssnNumber;
int arrayCount;
public SSNArray(){//defult contructor
ssnNumber = new String[9999];
arrayCount = 0;
}
public SSNArray(int arraySize){
ssnNumber = new String[arraySize];
arrayCount = 0;
}
public String[] getSSNNumber(){
return ssnNumber;
}
public int getArrayCount(){
return arrayCount;
}
public boolean validateSSNNumber(String SSNFormat){
return SSNFormat.matches("\\d{3}-\\d{2}-\\d{4}");
}
public String addSSN(String SSNFormat){
if(validateSSNNumber(SSNFormat)){
return ssnNumber[arrayCount++] = SSNFormat;
}else{
return null;
}
}
#Override
public String toString(){
String str = "\nThe Social Security Number(s) you entered is(are):\n";
for(int x = 0; x < arrayCount; x++){/
str += ssnNumber[x] + "\n";
}return str;
}
}
Subclass 1
package SSNServerStorageExpanded;
public class SSNArrayExpanded extends SSNArray{
public SSNArrayExpanded(){
super();
}
public SSNArrayExpanded(int arraySize){
super(arraySize);
}
#Override
public boolean validateSSNNumber(String SSNFormat){
if(super.validateSSNNumber(SSNFormat)){
boolean duplicate = false;
for(int y = 0; y < arrayCount; y++){
if(ssnNumber[y].equals(ssnNumber[arrayCount])){
System.out.println("No duplicates allowed, please try again");
duplicate = true;
break;
}
}
if(!duplicate){
arrayCount++;
}
}
return true;
}
}
Mainclass
package SSNServerStorageExpanded;
import java.util.Scanner;
public class SSNArrayTestExpanded{
public static void main(String[] args){
SSNArrayExpanded SSNArrayExpandedObject = new SSNArrayExpanded();
Scanner input = new Scanner(System.in);
System.out.println("Initiating SSN Server Storage Expanded");
System.out.println("► Type 'EXIT' at any moment to close the program ◄\n");
boolean run = true;
while(run){
System.out.print("Enter your Social Security Number(XXX-XX-XXXX): ");
String ssnNumber = input.next();
if(ssnNumber.equalsIgnoreCase("EXIT")){
System.out.print(SSNArrayExpandedObject.validateSSNNumber(ssnNumber));
return;
}else if(SSNArrayExpandedObject.validateSSNNumber(ssnNumber)){
SSNArrayExpandedObject.addSSN(ssnNumber);
}else{
System.out.println("!Please use the format XXX-XX-XXXX!");
}
}
}
}
What am I doing wrong with my public boolean validateSSNNumber method under Subclass 1 or are there more errors in my code that I am not aware of?
In your subclass1 can you try this. You need to compare the SSNFormat String entered by user with the array values (you were comparing array values itself). Do not increase the array count here instead do it in addSSN function as you were doing.
#Override
public boolean validateSSNNumber(String SSNFormat){
if(super.validateSSNNumber(SSNFormat)){
boolean duplicate = false;
for(int y = 0; y < arrayCount; y++){
if(ssnNumber[y].equals(SSNFormat)){
System.out.println("No duplicates allowed, please try again");
duplicate = true;
break;
}
}
if(!duplicate){
return true;
}
}
return false;
}
In the SSNArray class use this function for adding SSN number without validating the SSNFormat again.
public String addSSN(String SSNFormat){
return ssnNumber[arrayCount++] = SSNFormat;
}
You can try using a Set, which will easily help you to check for any duplicates and will reduce your iteration over array.
Why cant you go for LinkedHashSet data structure for storing the ssn number.?, provides easy retrieval and duplicate check in an order of O(1).
final LinkedHashSet<String> ssnNumber;
also the code
#Override
public boolean validateSSNNumber(String SSNFormat){
if(super.validateSSNNumber(SSNFormat)){
boolean duplicate = ssnNumber.add(SSNFormat);
if(duplicate){
System.out.println("No duplicates allowed, please try again");
return false;
}
return true;
}
return false
}
Here is your complete Solution, with this you can add N-number of SSN-Number as you want,
import java.util.HashSet;
import java.util.Scanner;
class SSNSet{
final HashSet<String> allSsnNumber = new HashSet<String>();
public HashSet<String> getAllSsnNumber() {
return allSsnNumber;
}
public boolean validateSSNNumber(String SSNFormat){
return SSNFormat.matches("\\d{3}-\\d{2}-\\d{4}");
}
public boolean addSSN(String SSNFormat){
if(validateSSNNumber(SSNFormat)){
boolean flag;
if(allSsnNumber.add(SSNFormat)){
System.out.println("Added Successfully");
flag = true;
}else{
System.out.println("Duplicate Not Allow");
flag = false;
}
return flag;
}else{
System.out.println("!Please use the format XXX-XX-XXXX!");
return false;
}
}
}
public class SSNArrayTestExpanded{
public static void main(String[] args){
SSNSet SSNArrayExpandedObject = new SSNSet();
Scanner input = new Scanner(System.in);
System.out.println("Initiating SSN Server Storage Expanded");
System.out.println(" Type 'EXIT' at any moment to close the program \n");
boolean run = true;
while(run){
System.out.print("Enter your Social Security Number(XXX-XX-XXXX): ");
String ssnNumber = input.next();
if(ssnNumber.equalsIgnoreCase("EXIT")){
break;
/*System.out.print(SSNArrayExpandedObject.validateSSNNumber(ssnNumber));
return;*/
}else{
SSNArrayExpandedObject.addSSN(ssnNumber);
}
}
System.out.println("===============================================");
System.out.println("You have entered SSN Numbers are : ");
System.out.println(SSNArrayExpandedObject.getAllSsnNumber());
System.out.println("===============================================");
System.out.println("Program Ended Successfully");
}
}
and Output is :
Initiating SSN Server Storage Expanded
Type 'EXIT' at any moment to close the program
Enter your Social Security Number(XXX-XX-XXXX): 111-11-1111
Added Successfully
Enter your Social Security Number(XXX-XX-XXXX): 222-22-222
!Please use the format XXX-XX-XXXX!
Enter your Social Security Number(XXX-XX-XXXX): 111-11-1111
Duplicate Not Allow
Enter your Social Security Number(XXX-XX-XXXX): 333-33-333
!Please use the format XXX-XX-XXXX!
Enter your Social Security Number(XXX-XX-XXXX): 333-33-3333
Added Successfully
Enter your Social Security Number(XXX-XX-XXXX): EXIT
===============================================
You have entered SSN Numbers are :
[111-11-1111, 333-33-3333]
===============================================
Program Ended Successfully
public boolean validateSSNNumber(String SSNFormat) {
if (super.validateSSNNumber(SSNFormat)) {
/*
*Hashset add() - Returns true if this set did not already contain
*the specified element.
*If this set already contains the element, the call leaves the set
* unchanged and returns
*/
boolean duplicate = !uniqueSSNNum.add(SSNFormat);
return duplicate;
}
return false;
}
//To use HastSet it's better if you override equals and hashcode
//using the fields that you'll use for comparison equality
// generated using eclipse
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + arrayCount;
result = prime * result + Arrays.hashCode(ssnNumber);
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SSNArray other = (SSNArray) obj;
if (arrayCount != other.arrayCount)
return false;
if (!Arrays.equals(ssnNumber, other.ssnNumber))
return false;
return true;
}
I am at the end with this Java console. I can place one word when I add new text but when I try to add a sentence, I get errors! If someone can see something I missed or the problem I would appreciate it very much. It will work for one word just not two or more words.
This is two classes
The first class
package Billboard;
/*
* 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.
*/
/**
*
* #author Paul
*/
import java.util.Scanner;
public class BillboardMain {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
Billboard billboard = new Billboard();
while (true) {
System.out.println();
System.out.println();
System.out.println("\t Billboard Menu");
System.out.println();
System.out.println("Please select from the following billboard texts");
for (int i = 0; i < billboard.getMessages().size(); i++) {
System.out.println((i + 1) + ": "
+ billboard.getMessages().get(i));
}
System.out.println((billboard.getMessages().size() + 1)
+ ": Add new message.");
System.out.println((billboard.getMessages().size() + 2)
+ ": Show current text.");
System.out.println((billboard.getMessages().size() + 3) + ": Exit.");
System.out.println();
System.out.print("Choice: ");
int code = console.nextInt();
if (code == billboard.getMessages().size()+1) {
System.out.print("Enter new text here: ");
String newText = console.next();
billboard.addNewText(newText);
System.out.println("The new text message has been set to billboard");
} else if (code == billboard.getMessages().size() + 2) {
System.out.println("Current text is: " + billboard.getText());
} else if (code == billboard.getMessages().size() + 3) {
System.exit(0);
} else {
billboard.setText(code);
System.out.println("The text message has been set to billboard.");
}
}
}
}
The second class
package Billboard;
/*
* 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.
*/
/**
*
* #author Paul
*/
import java.util.ArrayList;
import java.util.List;
public class Billboard {
private String text;
private List<String> messages = new ArrayList<String>();
public Billboard() {
super();
messages.add("Neutral.");
messages.add("Enemies.");
messages.add("Friends.");
}
public List<String> getMessages() {
return messages;
}
public boolean addNewText(String newText) {
text = newText;
return messages.add(newText);
}
public String getText() {
return text;
}
public void setText(int index) {
if (index <= messages.size())
this.text = messages.get(index - 1);
else
throw new IndexOutOfBoundsException("Invalid message code.");
}
public String reverse() {
if (isEmpty())
return null;
else {
char[] chars = text.toCharArray();
char[] reverse = new char[chars.length];
for (int i = chars.length - 1, j = 0; i < 0; i--, j++) {
reverse[j] = chars[i];
}
return new String(reverse);
}
}
public String replace(char oldChar, char newChar) {
return text.replace(oldChar, newChar);
}
public String substring(int begin, int end) {
if (begin >= 0 && end < text.length()) {
return text.substring(begin, end);
} else
return null;
}
public boolean isEmpty() {
return text == null || text.isEmpty();
}
}
define another Scanner
Scanner console1 = new Scanner(System.in);
and replace: String newText = console.next();
with: String newText = console1.nextLine();
it should work
I currently have a validation method which returns a boolean based upon whether a given String is a valid Double, Float, Integer, Long, or Short. Whilst this seems to catch cases such as "asdf" as being an invalid string, it seems to fail when there is an invalid numeric string which starts with a series of numbers e.g.: "33asd". The method is shown below:
public static boolean isNumeric(String str, Class<? extends Number> cl) {
try {
if (cl.equals(Byte.class)) {
Byte.parseByte(str);
} else if (cl.equals(Double.class)) {
if (NumberUtils.convertStringToDouble(str, "###,###") == null) {
return false;
}
} else if (cl.equals(Float.class)) {
Float.parseFloat(str);
} else if (cl.equals(Integer.class)) {
Integer.parseInt(str);
} else if (cl.equals(Long.class)) {
Long.parseLong(str);
} else if (cl.equals(Short.class)) {
Short.parseShort(str);
}
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
The NumberUtils.convertStringToDouble method used above is:
/**
* #param number
* - The String to convert.
* #param format
* - The format of the string representation of the double (e.g:
* "###,###.00")
* #return The String as a java.lang.Double if its valid; otherwise null.
*/
public static Double convertStringToDouble(String number, String format) {
try {
NumberFormat num = new DecimalFormat(format);
return num.parse(number).doubleValue();
} catch (ParseException e) {
return null;
} catch (NullPointerException ne) {
return null;
}
}
As documented for DecimalFormat.parse,
parsing does not necessarily use all characters up to the end of the string
So, by the time the parser reaches the alphabet character, it already has something which parses into a legal number, and simply stops there.
I get an error message as follows: Exception in thread "main"
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at emp.MainClass.main(MainClass.java:52)
Using the following code, how do I alleviate this problem?
public class MainClass {
//main class
public static void main(String[] args){
// variable
String input;
boolean salaryError = true;
boolean dependentError = true;
boolean nameError = true;
boolean charError = true;
Employee emp1 = new Employee();
displayDivider("EMPLOYEE INFORMATION");
do{
input = getInput(" First Name");
nameError = nameValidate(input);
if(!nameError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
}while(!nameError);
emp1.setfirstName(input);
do{
input = getInput(" Last Name");
nameError =nameValidate(input);
if(!nameError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
}while(!nameError);
emp1.setlastName(input);
do{
input = getInput(" Gender: M or F");
charError = characterChecker(input.charAt(0));
if(!charError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
}while(!charError);
char g = input.charAt(0);
emp1.setgender(g);// validates use of M or F for gender
do{
input = getInput(" number of dependents");
dependentError = integerChecker(input);
if(!dependentError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
}while(!dependentError);
emp1.setdependents(Integer.parseInt(input));
do{
input = getInput(" annual salary");
salaryError = doubleChecker(input);
if(!salaryError){
JOptionPane.showMessageDialog(null,"Incorrect Input. Please Try Again!");
}
} while(!salaryError);
emp1.setannualSalary(Double.parseDouble(input));
emp1.displayEmployee();//displays data for emp1
Employee emp2 = new Employee("Speed","Racer",'M',1,500000.00);
displayDivider("EMPLOYEE INFORMATION");
emp2.displayEmployee();// displays data for emp2
terminateApplication(); //terminates application
System.exit(0);//exits program
}//end of main
// gets Input information
public static String getInput(String data)
{
String input = "";
input = javax.swing.JOptionPane.showInputDialog(null,"Enter your " + data);
return input;
}// end getInput information
// The display divider between employees
public static void displayDivider(String outputLab)
{
System.out.println("********" + outputLab + "********");
}// end display divider
// Terminates the application
public static void terminateApplication()
{ javax.swing.JOptionPane.showMessageDialog(null,"Thanks for the input!");
}// end terminateApplication
public static boolean doubleChecker(String inStr){
boolean outBool = true;
double tmpDbl = 0.0;
try{
tmpDbl = Double.parseDouble(inStr);
if(tmpDbl <= 0)
throw new IllegalArgumentException();
}
catch (Exception e){
outBool = false;
}
return outBool;
}
public static boolean integerChecker(String intStr){
boolean outBool = true;
int tmpInt = 0;
try{
tmpInt = Integer.parseInt(intStr);
if(tmpInt <= 0)
throw new IllegalArgumentException();
}
catch (Exception e){
outBool = false;
}
return outBool;
}
public static boolean nameValidate(String str){
for(char ch : str.toCharArray()){
if(!Character.isDigit(ch)){
return true;
}
}
return false;
}
public static boolean characterChecker(char gen){
boolean outBool = true;
try{
if(!( gen ==( 'M') || gen ==('F')))
throw new IllegalArgumentException();
}
catch (Exception e){
outBool = false;
}
return outBool;
}
}//end of Main Class
Your string is length 0. Make sure string.length() > 0 before accessing its elements. The problem is at the line the exception says the problem is on.
Better answer: are you using an IDE? If so, observe the line the exception tells you you have an error on. Set a breakpoint before that line, debug, and note the contents of the object on which the error happened (in this case the string). Then check the javadoc for the method that threw the exception to see if there is any problem calling that method on that string.
If you are not using an IDE, you will either need to use one or find a standalone debugger. Having a good debugger is a requirement of Java development.
This should save you a lot of SO questions going forward.
StringIndexOutofBoundsException means you're try to access the String using an index and the index is either negative or greater than the size of the string.
You're wrong in this part:
charError = characterChecker(input.charAt(0));
Because you're not check if the input length is 0.
Try to change that line to this:
charError = input != null && input.length() > 0 && characterChecker(input.charAt(0));