Question for Java Programmers

Page 2 - Seeking answers? Join the AnandTech community: where nearly half-a-million members share solutions and discuss the latest tech.

AgaBoogaBoo

Lifer
Feb 16, 2003
26,108
5
81
Originally posted by: dighn
you apply that to the parsed integer, not the string :)

I still get the same error.... hmmm. What exactly do you mean by "apply?" Oh yeah, incase you guys haven't noticed, this is my first program except for Hello World and fixing two easy programs by removing a few \n's.
 

notfred

Lifer
Feb 12, 2001
38,241
4
0
You're doing way too much work for this. Also, you shouldn't do stuff like negate the user's input. If the user enters -3 and your program does a calculation based on 3, it looks to the user like a bug in the program. If the user inputs -3 and gets back "Error: please enter a non-negative integer" then he knows he's doing something wrong. And you don't even want to get into parsing text like "3 pennies" what are you going to do next, start parsing input in the format of "three" or "2 dozen"? If the number isn't a non-negative integer, you should print an error message and have the user re-enter his input.
 

RaynorWolfcastle

Diamond Member
Feb 8, 2001
8,968
16
81
Originally posted by: notfred
You're doing way too much work for this. Also, you shouldn't do stuff like negate the user's input. If the user enters -3 and your program does a calculation based on 3, it looks to the user like a bug in the program. If the user inputs -3 and gets back "Error: please enter a non-negative integer" then he knows he's doing something wrong. And you don't even want to get into parsing text like "3 pennies" what are you going to do next, start parsing input in the format of "three" or "2 dozen"? If the number isn't a non-negative integer, you should print an error message and have the user re-enter his input.

see my original solution...
 

AgaBoogaBoo

Lifer
Feb 16, 2003
26,108
5
81
Originally posted by: AgaBooga
Originally posted by: dighn
you apply that to the parsed integer, not the string :)

I still get the same error.... hmmm. What exactly do you mean by "apply?" Oh yeah, incase you guys haven't noticed, this is my first program except for Hello World and fixing two easy programs by removing a few \n's.

Wait, I fixed it but now it shows the outputs as 0
 

AgaBoogaBoo

Lifer
Feb 16, 2003
26,108
5
81
Originally posted by: RaynorWolfcastle
Originally posted by: notfred
You're doing way too much work for this. Also, you shouldn't do stuff like negate the user's input. If the user enters -3 and your program does a calculation based on 3, it looks to the user like a bug in the program. If the user inputs -3 and gets back "Error: please enter a non-negative integer" then he knows he's doing something wrong. And you don't even want to get into parsing text like "3 pennies" what are you going to do next, start parsing input in the format of "three" or "2 dozen"? If the number isn't a non-negative integer, you should print an error message and have the user re-enter his input.

see my original solution...

Can you show me an example of these solutions based on your answer?
 

RaynorWolfcastle

Diamond Member
Feb 8, 2001
8,968
16
81
Originally posted by: AgaBooga

Can you show me an example of these solutions based on your answer?

I don't understand your question... In any event, the code will work "as is" if you rename the variables appropriately

 

AgaBoogaBoo

Lifer
Feb 16, 2003
26,108
5
81
Originally posted by: notfred
Here's your example

Thank You! I really appreciate your help! I'm gonna go back and understand what it means, but that is really helpful.

I have a few questions though.

1. Why does int number = -1; have to be used and what is its purpose?
2. Can you explain basically what each of the first 8 lines of the new code at the bottom do starting with public?
3. What can cause an IOException?
 

AgaBoogaBoo

Lifer
Feb 16, 2003
26,108
5
81
bump... I'd appreciate some answers. Also, dighn, I tried the first code you gave me and it a value of 0 whether the value was entered or not. Also, using the if statements, how would I say that if the answer is a negative, to ask the question again? I see notfred's code does this, but I don't understand this and if the teachers asks, I'll have no clue what to say except that I got it off of a website, which isn't a good thing.
 

notfred

Lifer
Feb 12, 2001
38,241
4
0
Originally posted by: AgaBooga
Originally posted by: notfred
Here's your example

Thank You! I really appreciate your help! I'm gonna go back and understand what it means, but that is really helpful.

I have a few questions though.

1. Why does int number = -1; have to be used and what is its purpose?
2. Can you explain basically what each of the first 8 lines of the new code at the bottom do starting with public?
3. What can cause an IOException?

1) I declare an integer and initialize it to -1, why -1? I'll get to that in a second.

2)
public static int getInput(BufferedReader dataIn, String prompt){

This line declares a new method. You already have one methos declared (main) but your teacher may not have described how they work yet. Basically it's a section of code that can be reused from somewhere else. if you see earlier in the file I have lines like "amtQuarters = getInput(dataIn, "How many quarters are there?");" where the method I wrote is used. These are called "method calls" and each time one is run, it sends some information to the method, and gets different information back from the method, all in one line of code.

Info about my specific method:
for now you can ignore "public" and "static" as they're really more advanced topics that you'll cover later. "int" specifies the return type of the method. All that means is that the method is finished, the type of data that it will have created is an int. You can create methods with any return type you like, doubles or Strings for example.

"getInput" is the name of my method, it's there so I can call it later on.

The stuff in parentheses are arguments to the method. Arguments are data that the method requires in order to run. My method has two arguments: One is a bufferedReader that I name "dataIn" the other is a String that I name "prompt"

now, since the method is of type "int" you can use it in place of an integer.

Let's define a hypothetical integer:

int number = 1;

Or, we can do the same thing with our method:

int number = getInput(someBufferedReader, someString)

Since, the method is of type integer, we don't know what integer it will end up being when it's done executing, but we know that it will be SOME integer.

You can see that is what I did earlier in the program with lines like: amtQuarters = getInput(dataIn, "How many quarters are there?");

Now, what happens inside the method when it runs:
This requires a little more discussion of arguments...
I have the arguments:
bufferedReader dataIn
and:
String prompt

Using these as arguments is similar to having these two lines at the beginning of the method:
bufferedReader dataIn;
String prompt;

However, since they're arguments, they will already have data assigned to them. The data that they have assigned to them is dependent on what was used in the method call. Here's an example.
One of my method calls from your program:
amtQuarters = getInput(dataIn, "How many quarters are there?");
now you can see that the first argument is "dataIn". That is the "dataIn" that you declared on the 7th line of the program. It gets sent to my method, where I also call it "dataIn".
The second argument is the string "How many quarters are there?"

Now, referring to earlier when I said that arguments were kind of like variable declarations at the beginning of a method, if we use this example, we have these two variable declarations:
bufferedReader dataIn = dataIn // The one after the "=" is the one from the top of the program.
string prompt = "How many quarters are there?";

if you're confused about how we can have two different variables named "dataIn", it's an issue called "variable scope". It basically says that you can re-use variable names as long as they're inside different functions. There's a lot more to the topic of variable scope if you're interested.

Ok, so that's the discussion on arguments. Now what does my code do? Let's start here:
int number = -1;
This declares an integer and sets it to -1. You'll see why I used -1 in a minute.

String input = new String();
This makes a new, empty string for us to use.

while (number < 0){
This begins a while loop. A while loop will repeat itself as long as the condition inside the parentheses is TRUE. Basically, when you start a while loop, the computer executes the code in the parentheses. If it's true, it executes all the code inside the {} that follows the parentheses. When it gets to the closing }, it goes back to the parentheses, and checks again. If the condition is still true, it does it again. As soon as it NOT TRUE the computer skips the {} after the parentheses, and continues on to the next section of code.

Now, you see that my code inside the parentheses is "number < 0". When we start the while loop, "number" is set to "-1". The computer evaluates the code inside the parentheses: "-1 < 0". That is, obviously true, so the computer starts running the code inside the {}. The reason I initialized "number" to -1 is to force the while loop to run at least one time. If I had set number initially to 0 for example, the computer would have looked inside the parentheses and evaluated it like this: "0 < 0". That is not a true statement, so the computer would have skipped the while loop, which is not what I wanted.

try{
Try is used in exception handling. It is paired with a "catch" statement later in the code. I'll explain more when I get to catch.

System.out.println(prompt);
This just prints out the String that we got earlier as an argument.

input = dataIn.readLine();
This reads from the bufferedReader that we got as an argument, and assigns it to our string "input".

number = Integer.parseInt(input);
You did this earlier, it converts a String into an Integer. One important note is that parseInt will throw a NumberFormatException if the String it gets doesn't look like an integer. We'll get to this also when I cover "catch".

if(number < 0){
System.out.println("Error: You must enter a non-negative integer");
}
This checks to see if our number is less than 0. If it is, it prints an error message.

catch(NumberFormatException e){
Ok, so "catch" watches for exceptions. It looks at any of the code in a preceding "try" block, and if that code throws out any exceptions, the "catch" block will deal with them so that the program wont crash. That's what the "try" block is for, just deciding which code the "catch" block is listening to.

In our "catch" line, we're specifically looking for an exception of type NumberFormatException. If any are generated, this catch block of code will run instead of the program crashing.
Now, when you run the line "number = Integer.parseInt(input);" it has the possibility of generating one of these exceptions. If it does, then the computer skips ahead from the "number = Integer.parseInt(input);" line, directly to the "catch" line. Once we get to the catch block, we just print a friendly error message, and the program doesn't crash.

We have one more "catch" line that looks for IOException errors. Theline we have that might generate these errors is "input = dataIn.readLine();" If your bufferedReader had been attached to a file, it's possible that you'd get an IOException if the hard drive was unplugged in the middle of reading your file, or if someone deleted the file while you were reading it. Since your bufferedReader is attached to the terminal, it's unlikely that you'd get an IOException, but bufferedReader still wants you to make sure that you catch it in the event that one does occur.

Now, after we finish this "catch" block, we have the closing "}" for our while loop. When we get to this point, the computer checks to see if "number" is less than 0 again. If it's not, because someone entered a negative number, or they entered something that caused an exception, we go back to the top of the while loop and do it again. If someone entered a valid number, it's either equal to or greater than 0, and we continue on the next line.

return number;
"return" says "Ok, this method is done, take "number" (which, you'll notice is an integer, which is the same type as our method) and send it back to the place where this function was called.

So "number", whatever the user entered, is sent back to the line that called our method in the first place and the line:
amtQuarters = getInput(dataIn, "How many quarters are there?");
Becomes:
amtQuarters = "number" that our method just returned.

I hope that makes sense. I tried to write geared toward a beginner level. Damn that was a long post.
 

notfred

Lifer
Feb 12, 2001
38,241
4
0
Originally posted by: AgaBooga
Oh yeah, what do the "e" on those two exceptions mean?

"e" is just the name of the exception we get. It's like an argument as described in my last post (the super long one). We don't actually use the exception object, so I just gave it a short crappy name because java will complain if you don't give it any name at all.
 

dighn

Lifer
Aug 12, 2001
22,820
4
81
Originally posted by: AgaBooga
bump... I'd appreciate some answers. Also, dighn, I tried the first code you gave me and it a value of 0 whether the value was entered or not. Also, using the if statements, how would I say that if the answer is a negative, to ask the question again? I see notfred's code does this, but I don't understand this and if the teachers asks, I'll have no clue what to say except that I got it off of a website, which isn't a good thing.

first i should say that you should do what notfred did. negating the value without giving the user any prompt is bad behaviour.

anyway, you are doing something wrong, here is how it's supposed to be done if you just want to negate it:

input = dataIn.readLine();
number = Integer.parseInt(input);

if(number < 0) number = -number;
 

Noirish

Diamond Member
May 2, 2000
3,959
0
0
don't assume user knows what to enter (trust me there is no bug in program, it's always user error ;))
anyway, it should prompt the user to enter a number made up of numeric values (0-9) and maybe decimal points too.
it's always good to be precise about what type of values you ask of the users.
read notfred's post like java bible :)
 

halik

Lifer
Oct 10, 2000
25,696
1
81
Originally posted by: notfred
I didn't read the whole thread:

try{
number = however you're reading input goes here;
}
catch(NumberFormatException e){
number = 0;
}

this is by far the easiest solution,
the user is inputing stuff thats not an integer and java freaks out
 

AgaBoogaBoo

Lifer
Feb 16, 2003
26,108
5
81
Wow, notfred, I want to thank you for that great post you made, and I'll now be carrying a "Notfred for Elite" line in my sig. Incase you read this really fast, give it a few minutes, hehe. I'm going to use that solution that you posted. Your post was very helpful and easy to understand for a person at my level beginning to program. Thanks again!
 

Kntx

Platinum Member
Dec 11, 2000
2,270
0
71

I didn't read the thread so im not sure if it's been answered but...

do this.

try
{
x = Integers.ParseInt(theThingYouWantToParse);
}
catch(NumberFormatException e)
{
//no parseable int
}