• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

cannot find symbol compile error

 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello everyone,

I've decided to register to the forum as I've become increasingly aware of the friendly community here!

I'm totally new to programming altogether and after almost reaching half way in the 'Head first java' book I decided to try and apply some of what I've learnt so far and write my first 'Object orientated' program. As this is pretty much the first program I've ever written, I decided to write a program to ask for two integers and add them both together and then present them to the user (the goal eventually being a basic fully working command line calculator with +,-,* and /. I'm expecting many compile errors but not the following errors below (which I need help with).

I have three .java files contained within a folder and after trying to figure out how to compile all three files (as they use one another) all at once, I came across this ---> javac *.java

so I typed this in the command line whilst in the directory containing the three files assuming *.java is the best approach and then I receive the following errors:

inputOutput.java:10: error: cannot find symb
c.addition() = intIn.nextInteger();
^
symbol: variable c
location: class inputOutput
inputOutput.java:10: error: cannot find symb
c.addition() = intIn.nextInteger();
^
symbol: method nextInteger()
location: variable intIn of type Scanner
inputOutput.java:14: error: cannot find symb
int displayThis = c.getTotal();
^
symbol: variable c
location: class inputOutput
setUpCalc.java:3: error: cannot find symbol
inou.numsToAdd();
^
symbol: variable inou
location: class setUpCalc
setUpCalc.java:4: error: cannot find symbol
inou.numsToOutput();
^
symbol: variable inou
location: class setUpCalc
5 errors


...and here is the source code from each .java file (like I said I'm expecting a lot of errors but first I need to understand why I'm receiving errors relating to my object reference variables, I'm sure you will see from the source code what I'm trying to achieve, also I must mention that I realise the program is overly complicated, my goal was to simply practice an object orientated approach rather than using the main method for everything).

setUpCalc.java


inputOutput.java



Calculate.java



Thank you very much for your time, any additional feedback is welcome as I'm sure you can see I'm eager to learn!

David
 
Rancher
Posts: 3742
16
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
For the first three you haven't declared the c variable and the last two you haven't declared the inou variable in the relevant classes.

And in future UseCodeTags when posting code. It makes it a lot easier to read.
 
Bartender
Posts: 4568
9
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi David. Welcome to the Ranch!

I've fixed the code tags for you. It looks like you added them correctly (thanks!), but the "Disable BB Code in this message" box had been ticked, which turns them off.

About the error, Joanne is right. All variables in Java need to be declared, and all the cases where the compiler says "cannot find symbol" are because the variable hasn't been declared so the compiler doesn't recognise it.
 
David Thompkins
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for both of your replies!

I've had a look again at both the compile errors and the source code. Starting with the first couple of errors relating to the c variable am I correct in believing the inputOuput class requires object reference variable c to be declared there too in some form?

In fact... it may be far better if you could point me in the right direction by simply correcting my object reference variable c and it's deceleration so I can see what I've done incorrectly, as to me (a total beginner) it appears I've already declared reference variable c in the Calculate class.

If I appear to have bitten off more than I can chew by creating this program and should maybe consider starting something even simpler then let me know, many thanks and much appreciated.

p.s thank you for informing me of the 'disable BB code option' Matthew, I had no idea as to why the code was not displaying correctly after using code tags!

David
 
Bartender
Posts: 3323
86
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

David Thompkins wrote:In fact... it may be far better if you could point me in the right direction by simply correcting my object reference variable c and it's deceleration so I can see what I've done incorrectly, as to me (a total beginner) it appears I've already declared reference variable c in the Calculate class.


If we simply correct your code for you you won't learn as much as when we tell you what is wrong and you correct it yourself.
We aren't trying to take the easy option here as it would be far quicker for us to just correct the code than to explain to you what is wrong and then answer follow up questions. It really is for your benefit in the long run - we are being cruel to be kind

BTW You should use standard Java naming conventions, for example all class names start with an upper case letter.
 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

David Thompkins wrote:... as to me (a total beginner) it appears I've already declared reference variable c in the Calculate class.



BTW, as another note, it is not a good idea to have an instance variable of type Calculate class, that will be instantiated in the Calculate class. When you do this, it means that when you instantiate a Calculate class, part of the process, is the instatiation of a Calculate class for the instance variable, and part of the process for that instance, is another instatiation of a Calculate class for the instance variable, and part of the process for that instance, is another instatiation of a Calculate class for the instance variable, and part of the process for that instance, is another instatiation of a Calculate class for the instance variable, and part of the process for that instance, is another instatiation of a Calculate class for the instance variable, and part of the process for that instance, is another instatiation of a Calculate class for the instance variable, and part of the process for that instance, is another instatiation of a Calculate class for the instance variable, and part of the process for that instance, is another instatiation of a Calculate class for the instance variable, and part of the process for that instance, is another instatiation of a Calculate class for the instance variable, and part of the process for that instance, is another instatiation of a Calculate class for the instance variable, and part of the process for that instance, is another instatiation of a Calculate class for the instance variable, and part of the process for that instance, is another instatiation of a Calculate class for the instance variable, and part of the process for that instance, is another instatiation of a Calculate class for the instance variable, and part of the process for that instance, is another instatiation of a Calculate class for the instance variable, and part of the process for that instance, is another instatiation of a Calculate class for the instance variable, and part of the process for that instance, is another instatiation of a Calculate class for the instance variable, and part of the process for that instance, is another instatiation of a Calculate class for the instance variable, and part of the process for that instance, is another instatiation of a Calculate class for the instance variable, and part of the process for that instance, is another instatiation of a Calculate class for the instance variable, and part of the process for that instance, is another instatiation of a Calculate class for the instance variable, and part of the process for that instance, is another instatiation of a Calculate class for the instance variable, and part of the process for that instance, is another instatiation of a Calculate class for the instance variable, and part of the process for that instance, is another instatiation of a Calculate class for the instance variable, and part of the process for that instance, is another instatiation of a Calculate class for the instance variable, and part of the process for that instance, is another instatiation of a Calculate class for the instance variable, and part of the process for that instance, is another instatiation of a Calculate class for the instance variable, and part of the process for that instance, is another instatiation of a Calculate class for the instance variable, and part of the process for that instance, is another instatiation of a Calculate class for the instance variable, and ... blah blah blah ... part of the process for that instance, is another instatiation of a Calculate class for the instance variable, and part of the process for that instance, is another instatiation of a Calculate class for the instance variable, and part of the process for that instance, is another instatiation of a Calculate class for the instance variable, and part of the process for that instance, is another instatiation of a Calculate class for the instance variable, and part of the process for that instance, is another instatiation of a Calculate class for the instance variable, and part of the process for that instance, is another instatiation of a Calculate class for the instance variable, and part of the process for that instance, is another instatiation of a Calculate class for the instance variable, and part of the process for that instance, is another instatiation of a Calculate class for the instance variable, and ... out of memory error !!

[EDIT: okay, so I have a spelling error, which is very difficult to fix, when the error has be cut-n-pasted a few dozen times... ]

Henry
 
Ranch Hand
Posts: 82
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
As yourself mentioned, there is a general lack of knowledge in regards to variable scope and object oriented programming expressed here. As mentioned above, we don't flat out fix your code but I can offer some general ideas

1) Those 3 classes are not tied together or related to each other in any way, they are there own separate entity. That being the case, declaring a variable in 1 class does not allow you to call that variable in another class.
2) If you want to access another variable or class instance from the method/function of another class, then you need to pass that data via the method parameters.
3) As mentioned, you don't need/want to declare an instance of your class inside your class...there is no need. For example, you don't need to declare an instance of Calculate inside the Calculate class in order to call c.setNums(total) from the addition method. You can delete the instance declaration and simply call setNums(total)
4) You really want to declare you class instances in your main and then go from there, passing the data around and such.

Hope that gets you going in the right direction.
 
David Thompkins
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Tony,

I understand what you are saying, however I fear this issue may be something I simply have not learnt yet. If the solution to fix the deceleration for lets say reference variable c... is something I can simply work out by reviewing my code and looking at the compile errors (which I've done before your post and again after) then I wouldn't ask for any of you to post a fix for the solution as I agree it's better for myself to work it out.

This is what I've done to try and fix the c declaration since your post Tony,

...based on my assumption that the InputOutput class has no idea what the purpose of c is and from what I can gather from the compile errors.

I thought I'd try declaring c in the InputOutput class as shown below (knowing there's a good chance that it will not work):

InputOutput.java



...and in the Calculate class I placed // before the Calculate c = new Calculate(); that exists there to ensure I'm not creating to separate instances/objects of the Calculate class. I received multiple compile errors as I'm sure you all know, I will not bother pasting them here as it's clearly the incorrect solution to my problem, in fact I received an extra 2 errors.

I'm wondering... must I somehow import the Calculate class into the InputOutput class? and also import the InputOutput class in the Calculate class? by this I mean declare import CLASS NAME, as I did when importing the Scanner class from the Java API...

Thanks,

David
 
Raymond Holguin
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It appears your not using an IDE otherwise it would be screaming at you with the errors in your code as well as how to fix them (most IDE's at least). Similar to how your importing the class import java.util.Scanner; you also need to import Calculate and any other class you wish to use inside that particular class. I would suggest using some sort of IDE instead of a text editor, especially for beginners.
 
Sheriff
Posts: 7125
184
Eclipse IDE Postgres Database VI Editor Chrome Java Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Let's start with this code, as it's the first thing to run:



You're the compiler. You come across inou. What is it? What type is it? Without the type, how do you know if it has numsToAdd()?

So the compiler needs to know which type inou is, and if it's an object (hint: it is), an object needs to be created.

So how should you declare inou?

How do you create an object that inpu will reference?
 
David Thompkins
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Many thanks for all of your replies, I have had quite a few since Tony's post which I replied to so I will check them out tomorrow with fresh eyes.

David

p.s you're correct Raymond, I'm not using an IDE as head first java (the book I'm currently reading) stated I should use a simple text editor to begin with. (Using sublime text 2).
 
Henry Wong
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Raymond Holguin wrote:It appears your not using an IDE otherwise it would be screaming at you with the errors in your code as well as how to fix them (most IDE's at least). Similar to how your importing the class import java.util.Scanner; you also need to import Calculate and any other class you wish to use inside that particular class. I would suggest using some sort of IDE instead of a text editor, especially for beginners.



I completely disagree here. There is a huge disadvantage with learning with an IDE -- especially when you are just starting out. You don't get to understand all the details as the IDE is hiding many of them from you.

Also, while the IDE can make suggestions to get rid of compile errors, it is doing just that... getting rid of compile errors. Just because something compiles, doesn't mean it works. When you don't understand the code, all getting rid of a compile error does, is having code that you don't understand that compiles.

Henry
 
Knute Snortum
Sheriff
Posts: 7125
184
Eclipse IDE Postgres Database VI Editor Chrome Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think I agree with the Head First book that you should stick with a text editor for now.
 
lowercase baba
Posts: 13089
67
Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

David Thompkins wrote:p.s you're correct Raymond, I'm not using an IDE as head first java (the book I'm currently reading) stated I should use a simple text editor to begin with. (Using sublime text 2).


And most people here would agree 100% with this - not nec. the specific editor, but the idea to not use an IDE at first.
 
Raymond Holguin
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
well everyone has there own way of learning, you can stick with yours and ill stick with mine. I believe the pro's outweigh the con's, but again that was just my learning experience.
 
Marshal
Posts: 79151
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You were obviously lucky. Most people have found the cons overwhelming the pros.

For a more experienced person, an IDE is very useful and makes programming faster but the learning curve for beginners usually means they cannot learn both programming and the IDE.
 
David Thompkins
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi everyone,

This is becoming ever more frustrating. The class names have been correct and now start with an upper case letter, I've removed the Calculate reference variable c from the Calculate class due to Henry explaining why it's very bad idea. I thought I was simply declaring a object reference instance variable (for the heap) as opposed to a local reference variable (for the stack) which I've just currently read in head first Java.

After reading what Raymond put --->

1) Those 3 classes are not tied together or related to each other in any way, they are there own separate entity. That being the case, declaring a variable in 1 class does not allow you to call that variable in another class.
2) If you want to access another variable or class instance from the method/function of another class, then you need to pass that data via the method parameters.
3) As mentioned, you don't need/want to declare an instance of your class inside your class...there is no need. For example, you don't need to declare an instance of Calculate inside the Calculate class in order to call c.setNums(total) from the addition method. You can delete the instance declaration and simply call setNums(total)
4) You really want to declare you class instances in your main and then go from there, passing the data around and such.



After reading specifically these two lines of what Raymond said

2) If you want to access another variable or class instance from the method/function of another class, then you need to pass that data via the method parameters.

4) You really want to declare you class instances in your main and then go from there, passing the data around and such.



I tried this... in order to inform the methods in the InputOutput class of what reference variable c is and does.





which wasn't successful, I clearly need a way to link the classes together? or at least ensure each class knows what the object reference does.

I also took note of what Knute wrote

You're the compiler. You come across inou. What is it? What type is it? Without the type, how do you know if it has numsToAdd()?

So the compiler needs to know which type inou is, and if it's an object (hint: it is), an object needs to be created.

So how should you declare inou?

How do you create an object that inpu will reference?



in fact after reading both what Raymond and Knute wrote, I'm gathering the compiler always starts with the class which contains main and the jvm always runs from the class which contains main first as well, correct?

from the Calculate class.

This is now very time consuming,

am I even close to solving this problem?

Is this issue related to constructors in any way?

Thanks,

David

 
fred rosenberger
lowercase baba
Posts: 13089
67
Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

David Thompkins wrote:I tried this...which wasn't successful


What EXACTLY do you mean by "it wasn't successful"? Please remember that just saying "This doesn't work" doesn't tell us a thing about what happened - are their compiler errors? Does it run and crash? Does it run but give you the wrong output?

You need to remember that your job posting here is to make it as easy as possible for us to help you - and post the exact text of any error messages is critical for us to understand the problem.
 
Knute Snortum
Sheriff
Posts: 7125
184
Eclipse IDE Postgres Database VI Editor Chrome Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
David,

Don't worry too much about being frustrated. I've been programming for 30 years and I get frustrated.

You are getting closer. I assume your Calculate looks something like this:



Notice that you don't need an instance of the object to access methods that are in the class.

So what are your error messages when you compile? Mine looks like this:

InputOutput.java:10: error: method addition in class Calculate cannot be applied
to given types;
c.addition() = intIn.nextInteger();
^
required: int,int
found: no arguments
reason: actual and formal argument lists differ in length
InputOutput.java:10: error: cannot find symbol
c.addition() = intIn.nextInteger();
^
symbol: method nextInteger()
location: variable intIn of type Scanner
2 errors


So this is telling me that the method addition() in the Calculate class needs to be passed two ints. You need a way to save the input from intIn.nextInteger() and then pass both inputs at once to addition(). Make those changes, post your code and any error messages.
 
David Thompkins
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Fred, here are the errors I received from the command line:

InputOutput.java:11: error: method addition in class Calculate cannot be applied
to given types;
c.addition() = intIn.nextInteger();
^
required: int,int
found: no arguments
reason: actual and formal argument lists differ in length
InputOutput.java:11: error: cannot find symbol
c.addition() = intIn.nextInteger();
^
symbol: method nextInteger()
location: variable intIn of type Scanner
2 errors
 
Campbell Ritchie
Marshal
Posts: 79151
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You cannot put a method call to the left of the = operator.
 
David Thompkins
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Knute,

Thanks for the kind words I appreciate that.

You're correct my Calculate class is identical:



David

 
Knute Snortum
Sheriff
Posts: 7125
184
Eclipse IDE Postgres Database VI Editor Chrome Java Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Great. Now figure out how to save two inputs and pass them both at once to your addition method. Post your code and any errors. Good luck!
 
David Thompkins
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Knute,

firstly I'd like to say that Programming is bl**dy rewarding when something finally works!!! ...

So... after your last post I've been busy, very busy... trying to obtain user input and simply store the input inside a variable for now... (which I obviously had previously never done before or learnt from in head first java, there has been no mention of how to get user input as of yet).

So after creating and experimenting in a totally different program and some research over the internet I found a useful page on stackoverflow.com which had some useful info on obtaining user input.

Here is the simple short program,



I know I haven't yet figured out or even tried to take two lots of input (let alone call a method and send them) as I will continue with that later on this evening (and hopefully fix my calculator program as you mentioned I'm getting closer).

This was just an update to share my eureka moment!

p.s. Is this what makes programming addictive for most people? the fact that every now and then there's a sense of achievement when it before seemed almost impossible? One day I will look back at this post and laugh.

David
 
Tony Docherty
Bartender
Posts: 3323
86
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

firstly I'd like to say that Programming is bl**dy rewarding when something finally works!!! ...


Congratulations.
(Now are you glad we got you to fix it yourself)

David Thompkins wrote:p.s. Is this what makes programming addictive for most people? the fact that every now and then there's a sense of achievement when it before seemed almost impossible? One day I will look back at this post and laugh.


The little victories certainly help to keep you going and don't be fooled into thinking expert programmers don't struggle at times, as you progress you'll find no matter how good you get there's always another challenge up ahead.
 
Knute Snortum
Sheriff
Posts: 7125
184
Eclipse IDE Postgres Database VI Editor Chrome Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

p.s. Is this what makes programming addictive for most people? the fact that every now and then there's a sense of achievement when it before seemed almost impossible?



Oh yes! That and creating something with your "bare hands."
 
David Thompkins
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes I am glad I worked it out on my own (provided that means asking for more clues in this thread as they were most definitely needed, excessively trying to find solutions to the problems on a smaller scale in smaller programs, fixing errors one by one as they appear in the cmd and carrying out research over the internet, looking at other peoples solutions to getting and storing multiple input, trying to understand them and then seeing how I can use them).


Tomorrow I would like to see where else in the program I can declare the reference variables other than main.

So I'm proud to present my latest update of the program!







Is the code I wrote what you expected when you pointed me in the right direction by suggesting the following Knute? --->

Great. Now figure out how to save two inputs and pass them both at once to your addition method. Post your code and any errors. Good luck!



Tomorrow I will see how I can polish the program and experiment by seeing if I only need to declare the Import in the class with main() etc.

The ultimate goal being to create a calculator which performs basic tasks like subtraction, multiplication and division. I also need to be able to add more than two numbers together and so on.

Do you think that I've used the correct OO approach in the program?

Thanks for all of your support,

David
 
Tony Docherty
Bartender
Posts: 3323
86
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

David Thompkins wrote:Yes I am glad I worked it out on my own (provided that means asking for more clues in this thread as they were most definitely needed, excessively trying to find solutions to the problems on a smaller scale in smaller programs, fixing errors one by one as they appear in the cmd and carrying out research over the internet, looking at other peoples solutions to getting and storing multiple input, trying to understand them and then seeing how I can use them).


Rather than "I worked it out on my own", think of it more as "I got stuck, I asked the right questions and used the answers to fix it myself" - and that's what programming is all about.

Is the code I wrote what you expected when you pointed me in the right direction by suggesting the following Knute? --->


It's certainly one way of doing it but it's a bit restrictive as it doesn't allow the user to input more numbers. Another way is to ask the user to input a single number and put this code in a loop so the user is asked for a number, the number is added to the running total which is then displayed and then the loop repeats.

The ultimate goal being to create a calculator which performs basic tasks like subtraction, multiplication and division. I also need to be able to add more than two numbers together and so on.


In that case see my answer above but ask the user for an operator and then ask for a number and call the appropriate method based on the operator.

You may also want to look at error handling so the program can cope with someone inputting letters rather than numbers etc.

Do you think that I've used the correct OO approach in the program?


For a beginner I think you've done an excellent job. Many beginners would have attempted to write all this in the main method of one class.
 
David Thompkins
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Tony,

I've tried to break this next task down, so I've been focusing on allowing the user of my program to enter multiple numbers (not worrying about multiple types of user input or different operators for now). I started a new program and I'm using main() to simply test it all out, as this seems to be the best method for discovering new solutions to problems as opposed to trying to code in MyCalculator program and having to deal with all the extra confusion.

Here is the code so far, I assume the problem is that the int variable is able to store... well only... integers.



Surprisingly (for me at least), the code actually compiles, however when entering the '=' symbol I receive the following errors:

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at MultipleInput.main(MultipleInput.java:14)

I then decided to search the internet for a way to check if numbers are present in a string variable. The idea being... to get user input in the form of a string as opposed to nextInt() and store the input in a string variable. Then check the variable for integers, if integers are present add them together else if the '=' character is present then display the total variable (answer to sum).

However many of the solutions provided on stackoverflow I don't understand and I don't simply want to use code which I do not understand.

As it currently stands, this --> char decision = scan.next().charAt(0); doesn't quite make sense, obviously I understand the charAt(0) means scan the character at position 0 in the string, but why the extra dot operator, am I calling two methods?

What are your thoughts?

and do you have any hints?

Thanks,

David
 
Knute Snortum
Sheriff
Posts: 7125
184
Eclipse IDE Postgres Database VI Editor Chrome Java Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The key to understanding something like scan.next().charAt(0) is to think about what scan.next() returns. I think you know that it returns a String. So what does someString.charAt(0) return?

If you have an expression with more than one dot, you evaluate the expression from left to right.
 
Campbell Ritchie
Marshal
Posts: 79151
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You are telling the Scanner to provide you with an int and presenting it with an equals sign.

Another thing. Never use == false or == true or similar. They are not only poor style but also error‑prone because it is only a matter of time until you write = instead by mistake.
It is if (b)… or if (!b)…

You do realise that '=' is not an equals sign. A char is not a character or anything; it is a number. It is all in the Java Language Specification. And you can actually understand that section
That means you can use arithmetical operators on chars and actually get them to work. That includes the == operator. So the compiler will be quite happy about that, until you actually enter an = sign which the compiler “knew” nothing about.

You are trying to produce a calculator, aren't you? In that case, remember that you use operand‑operator‑operand‑operator‑etc. You alternate operators and operands. One number, one operator. So you get a number in the loop, then an operator, and you can stop when the operator is =. You can organise things so the input is 123 + 234 + 345 + 345 =
 
Tony Docherty
Bartender
Posts: 3323
86
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

David Thompkins wrote:Surprisingly (for me at least), the code actually compiles, however when entering the '=' symbol I receive the following errors:


It compiles because the compiler has no idea what the user is going to input so has to assume you know what you're doing.

David Thompkins wrote:I then decided to search the internet for a way to check if numbers are present in a string variable...
and do you have any hints?


Rather than read it in as a String and then try to interpret the value, the Scanner has an hasNextInt() method which might prove useful. I suggest you check out the API docs for the Scanner class.
 
Campbell Ritchie
Marshal
Posts: 79151
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Of course I was forgetting about the sign change operator. You will have to pretend that −123 is a single token representing a negative number, rather than what it really is, namely a positive number preceded by the sign change operator (often called unary minus). I think (not certain) that the Scanner will interpret "−123" as a number and return a negative result, so you should be all right. Just don't write − 123 with a space.
 
Campbell Ritchie
Marshal
Posts: 79151
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There is another way to use the Scanner on the input String. I posted about it recently and can't find it. You can pass a String to a Scanner's constructorI am pretty sure Tony was thinking of a different way to handle your input, which will actually make your code much neater and shorter.
 
David Thompkins
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Good morning everyone,

I have a few questions to clarify your recent replies.

Hi Knute, to clarify and ensure I understand what you've said. scan.next calls the next method in the scan class/object in the java API which somehow (I'm wise enough to not even attempt to understand how it does this for now) takes user input, processes it inside the next method and then returns the processed input in the form of a string, correct? so .... when looking at a method call which contains two dot operators, I first need to figure out what the first method call returns after the first dot operator (in this case it's a String like you mentioned). Then look at the code and now imagine that the next method (or whatever method call comes first) is replaced by what it returns, next I then look at what calling itsreturnedString.charAt(0) which... (correct me if I'm wrong) is me passing the charAt method the value 0 in the parenthesis of the method call (to say find and return the character which is at 0 in my string) and place variable, which happens to be decision.

I may have got this entirely wrong though, as a String is in fact a class? not a data type?

hmm I assumed after typing the above that the charAt method was also within the Scanner class, but apparently after a quick google search it's contained within the String class (which confirms what I previously wrote about is a String a class or a data type, it's clearly a class).

...and as the String class (please correct me if I'm wrong) is imported and declared to be used in all of our java programs (without us having to import it, as it's considered so essential?) that's how we can simply call the String's method... without having to say String.CharAt(0) first or import?

Apologies for all of those questions Knute I just what to ensure I understand,

I do have some more questions based on what Campbell and Tony posted, which I will ask in a little while, many thanks! David.

 
Knute Snortum
Sheriff
Posts: 7125
184
Eclipse IDE Postgres Database VI Editor Chrome Java Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

David Thompkins wrote:Good morning everyone,

I have a few questions to clarify your recent replies.

Hi Knute, to clarify and ensure I understand what you've said. scan.next calls the next method in the scan class/object in the java API which somehow (I'm wise enough to not even attempt to understand how it does this for now) takes user input, processes it inside the next method and then returns the processed input in the form of a string, correct?



Exactly. And the great thing is, you never have to understand how Scanner gets input. This is encapsulation: a class should expose its internal workings as little as possible.

so .... when looking at a method call which contains two dot operators, I first need to figure out what the first method call returns after the first dot operator (in this case it's a String like you mentioned). Then look at the code and now imagine that the next method (or whatever method call comes first) is replaced by what it returns, next I then look at what calling itsreturnedString.charAt(0) which... (correct me if I'm wrong) is me passing the charAt method the value 0 in the parenthesis of the method call (to say find and return the character which is at 0 in my string) and place variable, which happens to be decision.

I may have got this entirely wrong though, as a String is in fact a class? not a data type?



You have it entirely right! String is a class and a data type, in fact, all classes are data types! (It took me a while to realize this.)

hmm I assumed after typing the above that the charAt method was also within the Scanner class, but apparently after a quick google search it's contained within the String class (which confirms what I previously wrote about is a String a class or a data type, it's clearly a class).

...and as the String class (please correct me if I'm wrong) is imported and declared to be used in all of our java programs (without us having to import it, as it's considered so essential?) that's how we can simply call the String's method... without having to say String.CharAt(0) first or import?



Right, String is part of java.lang which is imported by default. I believe it is the only package that is. (Can anyone confirm?)

Apologies for all of those questions Knute I just what to ensure I understand,



No apology necessary. This is how you learn.
 
David Thompkins
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Campbell,

Never use == false or == true or similar. They are not only poor style but also error‑prone because it is only a matter of time until you write = instead by mistake.
It is if (b)… or if (!b)…



I understand why you mentioned using == is prone to error, however why is it poor style? I need a substitute for the ==, so I looked at

(b)… or if (!b)…

and I'm not sure what the b represents. I'm guessing if using == true/false is bad practice then so is saying == to anything else? like if (thisNumber == 5) {...}?
}
Were you hinting I use the following: which I read as while equalsEntered is set to anything-but true then do this {...} is that correct?





Also could you please expand upon what you mean by the following

A char is not a character or anything; it is a number

I've read "A Literal is the source code representation of a fixed value" on stackoverflow, they provided the following example:

boolean result = true;

boolean - is data type
true - is literal

so... a literal is basically the values a data type can hold?

and I found from the link you provided me campbell that char can hold the following values:

The following are examples of char literals:

'a'

'%'

'\t'

'\\'

'\''

'\u03a9'

'\uFFFF'

'\177'

'Ω'

however '=' is not included there... which seems strange since it compiles in my program, this is obviously where I'm confused.




Also when you wrote it seems as though your suggesting I can somehow ensure the compiler knows what the = symbol is?




I'm not quite sure what the quote below means, but I believe your mentioning an operator which is knew to me, the - known as the sign change operator? Also from what I gathered over the internet, a token is a sequence of characters or input.

Of course I was forgetting about the sign change operator. You will have to pretend that −123 is a single token representing a negative number, rather than what it really is, namely a positive number preceded by the sign change operator (often called unary minus). I think (not certain) that the Scanner will interpret "−123" as a number and return a negative result, so you should be all right. Just don't write − 123 with a space.



I may need to re-read about constructors in my head first java book to understand what you meant when you suggested using the Scanners consutrctor, it appears your solution extracts the integers from the input which is in the form of a String.



However!!! There is good news! I think I understand what you mean by

So you get a number in the loop, then an operator, and you can stop when the operator is =. You can organise things so the input is 123 + 234 + 345 + 345 =

although I may be incorrect we shall see!



phew..! Typing up that post was a work out!

David
 
David Thompkins
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
... and Tony I will check out the hasNextInt() method, I know sometimes the API docs can be rather difficult to understand but I'm sure that's normal for a beginner?
 
Knute Snortum
Sheriff
Posts: 7125
184
Eclipse IDE Postgres Database VI Editor Chrome Java Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

David Thompkins wrote:Hi Campbell,

Never use == false or == true or similar. They are not only poor style but also error‑prone because it is only a matter of time until you write = instead by mistake.
It is if (b)… or if (!b)…



I understand why you mentioned using == is prone to error, however why is it poor style? I need a substitute for the ==, so I looked at

(b)… or if (!b)…

and I'm not sure what the b represents. I'm guessing if using == true/false is bad practice then so is saying == to anything else? like if (thisNumber == 5) {...}?
}
Were you hinting I use the following: which I read as while equalsEntered is set to anything-but true then do this {...} is that correct?



Many Java structures take a boolean. In class, we are taught something like if (myInt == 5) { ... but what is sometimes unclear is that the expression myInt == 5 evaluates to a boolean.

But equalsEntered is already a boolean! When you write equalsEntered != true you're taking a boolean and evaluating it to a boolean! That's redundant. So when Campbell says "if (b) or if (!b)" he is saying, "Write if (<someVar>) where <someVar> is a variable of type boolean." Clearer?
 
David Thompkins
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Knute, when you wrote

all classes are data types

does that also go for classes which I make myself? would I be correct in saying my poodle is not only of type dog but is of data type dog? if a create the following object:

Dog poodle = new Dog();







String is part of java.lang which is imported by default. I believe it is the only package that is. (Can anyone confirm?)


I found this "For convenience, the Java compiler automatically imports three entire packages for each source file: (1) the package with no name, (2) the java.lang package, and (3) the current package (the package for the current file)..." on stack overflow

I'm not quite sure what the 2 other packages besides java.lang are, it seems as though they are related to programmer created packages, I haven't read about putting my classes into own packages in headfirstjava yet but it was briefly mentioned earlier in the book that' it's possible.

David
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic