I have the following method
how do I call the method from the main method? I want to keep typing in strings into the argument and when my string is equal to yes it prints "That's good", the loop then stops. I tried the following code in main method
but I get an error saying getScanner isn't applicable to string. Am I not passing the right arguments? We learned if we want to call a method we need to pass it an argument, if has a parameter. In this case, the parameter is scanner keyboard. Which I think is supposed to read from keyboard input, then run the loop.
1. Your method "getScanner" according to the name, suppose to instantiate a scanner and return to a caller. Anyway, probably there is no point to do that.
As you can simply create scanner by writing "Scanner in = new Scanner(System.in)", just don't think about closing that scanner at the end of your code if by any chance you're using clever IDE and it suggests to you to do that.
2. How strings equality are being checked? Have you been taught about that in your class? Please remind yourself by reading this tutorial.
3. Code indentation matters, please look in this guide, so you can see, how code should be formatted and indented.
4. Please work out your program first in english. I mean by describing your application in simple words without using any technical words. What needs to be done, what goes after what and please write down here. This way you'll solve this exercise likely sooner.
Never use != or == to check String identity.
You don't want to call such methods from the main method which is only there to start the app.
You can simply call getScanner from somewhere, but that is a poor name for that method because it does not get you a Scanner.
Beware of passing a Scanner pointing to a file or similar, which will give all sorts of weird and wonderful results … until it runs out of input and gives you an Exception.
Matthew Moreno wrote:okay, I see. I will change to
no, change it to
The '!' means 'not', so you have "while yes is not equal to i".
Moving "yes" to the front has a subtle benefit. When you use i.equals("yes"), it will throw an exception if 'i' is null. If you put "yes" first and 'i' is null it will return false.
Carey Brown wrote:. . . When you use i.equals("yes"), it will throw an exception if 'i' is null. If you put "yes" first and 'i' is null it will return false.
If you get input from a Scanner it never returns null. I have tried it. It either returns a real input (which might mean the empty String) or throws its own Exception. But you are right that there is that subtle benefit from writing the literal first.
See where your hand is? Not there. It's next to this tiny ad: