Can anyone help me with this? or alter the code of mine when it comes to the user Input

here's the block of code of mine

public int Remove(int i, Briefcase c[], String[] m) {

		int nChoice = 0;
		System.out.print("\tPlease remove " + i + " cases: ");
		nChoice = input.nextInt();
		if (c[nChoice] == null) {
			
			System.out.println();
			System.out
					.println("\tYou already entered that digit choose again\n");
			Remove(i, c, m);
			
		} else {
			System.out.println("\tI'm " + m[nChoice]
					+ " You just removed case # " + nChoice);
			System.out.println("\t|" + nChoice + "| contains $"
					+ c[nChoice].getAmount() + "\n");
		}
		return nChoice;
	}

what this basically do is when you enterd an index of an array and that array is null it will printout a message saying that you already entered a number. else it rwill return your choice. but the problem is when I enter a number larger than the bounds of an array it gives me and out bounds exception and also when I enter a letter or a negative number it also gives me an exception. soo how will I solve this? I want to keep on getting the users input after that the error is thrown he will not leave this block of code unless he entered the right number already, if I say right number, I mean not out of bounds and all of those other exceptions will be thrown.

Sorry for my bad english

Recommended Answers

All 29 Replies

try
{
//------------- Write your code here
}
catch(Exceptiontype object)
{
//--------- What will happen when error generate.
}

Generally u can use "Exception" to handle all kinds of exception but its not a proper way because you cant understand different type of exception then... Search down exception type in documentation and implement them.

Exactly. You can use exceptions to gracefully inform the user about the situation. But for this small program, its better if you perform a check using "if" to see if the value is ">size" or "<0". I recommend using the second mechanism (using checks). If the condition fails ask the user to give a different index

Here's a little pseudocode template that shows the general approach. It will loop asking for input and diagnosing exceptions and failed validation tests until good input is received

boolean inputIsOK = false;
while (! inputIsOK) {
  prompt user
  try {
    get input
    if (input < 0 && input >= size)  print error message
    else inputIsOK = true;
  } catch(Exception e) {
    print error message
  }
}

Here's a little pseudocode template that shows the general approach. It will loop asking for input and diagnosing exceptions and failed validation tests until good input is received

boolean inputIsOK = false;
while (! inputIsOK) {
  prompt user
  try {
    get input
    if (input < 0 && input >= size)  print error message
    else inputIsOK = true;
  } catch(Exception e) {
    print error message
  }
}

Here's my code , still an error though

public int Remove(int i, Briefcase c[], String[] m) {
		boolean inputIsOK = false;
		int nChoice = 0;
		while(! inputIsOK){
			System.out.println("Please Remove "+i+" cases");
			try{
				nChoice = input.nextInt();
				if(nChoice<0 && nChoice>=c.length && c[nChoice]!=null){
					System.out.println("Please try again");
				}else{
					inputIsOK = true;
				}
			}catch(Exception e){
				System.out.println("Invalid input");
			}
			
		}
		System.out.println("\tI'm " + m[nChoice]
		            					+ " You just removed case # " + nChoice);
		            			System.out.println("\t|" + nChoice + "| contains $"
		            					+ c[nChoice].getAmount() + "\n");
		            			return nChoice;
	}

refixed it but I am still getting errors when it comes to entering a letter and a negative number and out of bounds exception

public int Remove(int i, Briefcase c[], String[] m) {

		int nChoice = 0;
		boolean inputisok = false;
		while (inputisok == false) {
			System.out.print("\tPlease remove " + i + " cases: ");
			nChoice = input.nextInt();
			if (c[nChoice] == null || nChoice < 0 || nChoice > c.length | nChoice>m.length) {
				System.out.println();
				System.out.println("\tInvalid Input please Try again\n");
			} else {
				System.out.println("\tI'm " + m[nChoice]
						+ " You just removed case # " + nChoice);
				System.out.println("\t|" + nChoice + "| contains $"
						+ c[nChoice].getAmount() + "\n");
				inputisok = true;
			}
		}
		return nChoice;
	}

Please do not try to make me do all the work by saying "still an error". Do you think I am telepathic? This is the last such post I will respond to unless it has a complete description of the error, complete with full text of error messages or exception stackTraces as appropriate. :icon_wink:
Anyway:
nChoice<0 && nChoice>=c.length
must always be false, no value can less than zero AND >= length at the same time. Time to revise your binary operators???

Please do not try to make me do all the work by saying "still an error". Do you think I am telepathic? This is the last such post I will respond to unless it has a complete description of the error, complete with full text of error messages or exception stackTraces as appropriate. :icon_wink:
Anyway:
nChoice<0 && nChoice>=c.length
must always be false, no value can less than zero AND >= length at the same time. Time to revise your binary operators???

I am only dwelling when I input a negative number and a letter and each time I do that, I get an arrayoutofobounds Exception.
here's the error Please remove 6 cases: 32
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 32
at Player.Remove(Player.java:33)
at DealOrNoDeal.starGame(DealOrNoDeal.java:94)
at Play.main(Play.java:6)

Do you still get that problem after fixing your boolean operators?

Yes, and I am still wondering why am I getting these kind of errors :| though the condtions are fully understandable

OK, I just nticed you changed the order of the if as well as the operators

if (c[nChoice] == null || nChoice < 0 || nChoice > c.length | nChoice>m.length) {

This version executes c[nChoice] before testing whether nChoice is a valid index, hence outofbounds.

Isnt the problem obvious? Check ur If condition. You are first checking

c[nChoice] == null

What if nChoice is a negative or a letter or out of bounds of c[] ?? It throws an exception before checking other conditions in the if().

So use following pseudocode:

if( (WithinBounds) && (isADigit) )
{
      if(c[nChoice] == null)
      {
          inputIsOk=true;
          do work
      }
      else
           error: choice already chosen
}
else
    error: Invalid input

EDIT: Sorry james didnt notice your post... Redundant solution...

Isnt the problem obvious? Check ur If condition. You are first checking

c[nChoice] == null

What if nChoice is a negative or a letter or out of bounds of c[] ?? It throws an exception before checking other conditions in the if().

So use following pseudocode:

if( (WithinBounds) && (isADigit) )
{
      if(c[nChoice] == null)
      {
          inputIsOk=true;
          do work
      }
      else
           error: choice already chosen
}
else
    error: Invalid input

EDIT: Sorry james didnt notice your post... Redundant solution...

why is it that when c[nChoice] == null; it allows it? I mean I don't want users to enter a value, that is already nulled in the array since, each time the user picks a number that index of that array will be nulled

and how do I do the function? isADigit?

You need to test the index to be in the right range BEFORE you use it as an array index. You don't need to check for it being a number because you use getInt and it will throw an E if its not.

why is it that when c[nChoice] == null; it allows it? I mean I don't want users to enter a value, that is already nulled in the array since, each time the user picks a number that index of that array will be nulled

Im sorry it has to be !=null. I just copied from ur code.

And yeah as James said, getInt will throw InputMismatchException if u enter a letter. So u better find a way to catch that then loop back to input....

Sorry for the confusion :)

Im sorry it has to be !=null. I just copied from ur code.

And yeah as James said, getInt will throw InputMismatchException if u enter a letter. So u better find a way to catch that then loop back to input....

Sorry for the confusion :)

how do I catch that? should I use uhmm a an exception block?

Yup

try 
{
     read input
}
catch (InputMismatchException e)
{
     handle
}

I gave you a pseudocode template for all this yesterday

I am using that pesudocode already my problem is about that if it's a letter, is there anyfunction that will compare it if it's a digit? or no?

I gave you a pseudocode template for all this yesterday

Okay done. now my only problem that it keeps on looping if I enter the wrong choice but anyways here it is,

public int Remove(int i, Briefcase c[], String[] m) {

		int nChoice = 0;
		boolean inputisok = false;

		while (inputisok == false) {
			System.out.print("\tPlease remove " + i + " cases: ");
			
			try{nChoice = input.nextInt();}catch(InputMismatchException e){System.out.println("Wrong input ");}
			if (c[nChoice] == null || nChoice < 0 && nChoice >= c.length) {
				System.out.println();
				System.out.println("\tInvalid Input please Try again\n");
			} else {
				System.out.println("\tI'm " + m[nChoice]
						+ " You just removed case # " + nChoice);
				System.out.println("\t|" + nChoice + "| contains $"
						+ c[nChoice].getAmount() + "\n");
				inputisok = true;
			}
		}
		return nChoice;

Last time: if it's a letter then nextInt() will throw an exception, which you catch. nextInt returns an int, so its logically impossible for it to return a letter.

Please re-read the template. You changed it so that after catching an exception you go ahead and execute the rest of the code anyway.
line 10 still has the error that has been pointed out to you many times now. Are we wasting our time?

why not use a regex? get a string check if its completely made of 0-9 and if so convert it to Integer using parseInt().

Hi stevanity. His code uses nextInt, which returns an int or throws an E.
Yes, he can change it to read a String then do his own parsing, but why bother? Especially since he's already having so much difficulty with basic program flow and logical expressions.

Well, youre right James. He's struggling with basics.. Ok. We'll let him find the solution. Youve provided the pseudocode correctly... He can get it if he sits and writes down the flow...

@chiiqui

Do this.
Take a paper and pencil.
Write down what u want to do
write down what conditions u need to check
write a logical flow of the process
then convert to code.

Yeah! Come on chiiqui - you can do this. Re-read the advice you've been given and use stevanity's pencil & paper route to work through anything that's not clear.
Everyone struggles at first, but it gets easier...

Yeah! Come on chiiqui - you can do this. Re-read the advice you've been given and use stevanity's pencil & paper route to work through anything that's not clear.
Everyone struggles at first, but it gets easier...

Okay got it~! :D Thanks guys, lol :) . Thread closed please XD

Excellent! Please mark this thread "solved"

Thanks james cherill, btw I have no problems with the boolean operators , it just so happens some of my errors are typos lol, I think I need a better keyboard. but anyways thanks :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.