I'm trying to understand the difference, and benefits of using System.out.println() vs. return blah in a method.
It seems like System.out.println() is used to display static information, and return is a value returned from the method. Yet I'm seeing examples like the one below, where a function is used within the System.out.println() statement
System.out.println(name.substring(1, 3));
When is it right to use System.out.println() and return. Is it that return can be used by another piece of code later, whereas System.out.println() cannot?
Your last sentence is effectively correct, but the distinction between these two operations is HUGE, so I'd like to provide a more in depth explanation of their differences.
The Difference:
return is an instruction that controls the flow of your program's execution. It is a fundamental part of the Java syntax. It tells the computer what part of your code to execute, and what values to use during that execution. When you return a value, you are saying "The result of calling this method is XXXX" (with 'XXXX' being the value you returned).
System.out.println is not used to control how your program executes. It is a merely way to inform the user of what is going on inside your program. System.out.println (syso for short) can print any information to the console; it doesn't matter if it's a variable, an expression, or the result of a method call. There is no limitation to "static" data.
Let's look at both of them in action:
int addInts(int arg0, int arg1)
{
return arg0 + arg1;
}
This means that wen we call addInts in our program, it will evaluate to the sum of its arguments. So when we write addInts(3, 7), it's the same as if had simply written 3 + 7 or 10 in our source code. Nothing is printed to the console; all we've done is give our program a way of calculating something.
However, any calculations we might make are ultimately useless if all they do is sit inside the computer, so we need a way to display this information to the user. Enter syso:
System.out.println(addInts(22, 16));
The addInts method is called and returns 38. This value is placed somewhere in the computer's memory such that our program can find it.
Next, syso takes that value (38) and prints it to the console, letting the user know what value was calculated. Nothing new is calculated from this procedure, and our program continues to the next statement.
So which do I use?
In simple programs, you have so few values to keep track of that it can be tempting to just print everything that you want to know where you calculate it. For instance, if you were writing a program to do your algebra homework (I've been there) and you wrote a method to solve the quadratic equation, it might be tempting to structure it like this:
class Algebra
{
static void quadSolve(double a, double b, double c)
{
double result = /* do math... we're ignoring the negative result here*/;
System.out.println("The solution to the quadratic equation is: " + result);
}
public static void main(String[] args)
{
quadSolve(1.0, -6.0, 9.0);
}
}
However, this approach quickly becomes a very bad idea if you want to make your program a little more complex. Let's say one problem requires you to solve the quadratic equation and then use the result of that calculation to calculate the volume of a cylinder. In the above example, we can't do that: after we dump the value of result to the console via syso, it disappears when the quadSolve method ends. It would make much more sense if we have quadSolve return result and let the "caller" (the place quadSolve was called from) deal with handling that value. This is a much more flexible design that allows us to make our programs much more complicated with relative ease. This increased flexibility and modularity is really what makes methods useful. Here is the implementation:
class Algebra
{
static double quadSolve(double a, double b, double c)
{
double result = /* do math... we're ignoring the negative result here*/;
return result;
}
public static void main(String[] args)
{
double x = quadSolve(1.0, -6.0, 9.0);
//now we can do whatever we want with result:
//print it, negate it, pass it to another method-- whatever.
System.out.println("The solution to the quadratic equation is: " + x);
System.out.println("And it's square is: " + (x * x));
}
}
I hope this clears things up. Feel free to ask if you need additional clarification.
A method often returns a value (which is done by using the return statement).
Information may be "printed" to an output stream by System.out.println() references.
They both have their uses ... which are usually orthogonal.
They have very little to do with each other.
System.out.println() is used to output strings to a console/terminal. So
System.out.println("Hello world");
should output the string "Hello world"
return is a statement in Java to go back to the code that invoked the method and pass back a value.
public static int add(int a, int b) {
return a + b; // go back to method that called this method (main)
}
public static void main(String[] args) {
int sum = add(3,4); // the return result (7) is stored in sum
}
From my understanding, and to give a simple answer which has a significant meaning, I would say:
It is like when you go to a coffee shop and order a cup of coffee, but the barista tells you if you want a picture of the coffee cup or the cup itself :).
System.out.println() is the picture, while..
return blah is the cup of coffee.
With "return" you can do what you like with the value of return, but with "print" you only see what the function is doing.
Related
I'm trying to make a tic-tac-toe game and I'm encountering a lot of copy-paste work for inputs. I'm trying to figure out what design pattern and implementation works for prompting the user, collecting their input, comparing it and then acting by assigning a value. Right now my code looks like this.
public void promptPlayerCount(BufferedReader in) throws IOException {
String input;
// initial prompt
System.out.println("How many players?");
input = "try again";
while (input.equals("try again")) {
input = in.readLine();
// extract data and check it
switch (Integer.parseInt(input)) {
case 1:
// assignment
playerCount = 1;
break;
case 2:
playerCount = 2;
break;
default:
input = "try again";
// clarified instructions
System.out.println("please enter 1 or 2");
}
}
}
There's a part of me that thinks I could make a function (maybe a factory?) that allows me to generate a function by passing the constructing function the details of the initial prompt, the extraction method, the assignment action and the clarification message.
Would this be best done with lambda functions?
Text input is hard, especially if you can't trust your user (like in a game). Your parseInt will throw a nasty exception right off if your value isn't an integer.
Also standard in is not friendly. I assume this is for an assignment so I won't fault you for using it, but in anything where you don't HAVE to use stdin, don't. The problem is that it's amazingly difficult to get Java to respond to anything less than an entire line with an enter at the end.
When dealing with user input I almost always trim it (Just because they love to insert random white spaces at the beginnings and end) and check to see if it's empty. This could probably be put into a function that also either shows an error or exits the program on "Empty" and otherwise returns a string.
If you often want int values, write a second function that calls the first. Have the second function return an int, but have it catch the exception if the text is invalid and prompt the user again. You could even have this function take a "Range" of integers as a parameter and provide a prompt. So what you have above could look like this:
playerCount = getUserInput("Please enter the number of users", 1, 2);
The rest is wrapped in simple non-redundant functions.
Won't write the code for you because A) it's probably a homework assignment and the fun part is actually coding it and B) someone else probably will provide a full solution with code before I'm done typing this :(
Good luck.
I don't get why I have to use square() in this code? Why can't I just add n times n to the String s?
static int square(int n){
return n*n;
}
static void ausgabe(int n){
String s;
int i = n;
s = "SquareOf" + i + " = " + square(i);
Sysout(s);
}
my solution would be to miss out the square method and just add like this
s = "SquareOf" + i + " = " + i*i;
I tried and the result is always right. But our book suggests the first way and I would just like to know why they make it more complicated in my eyes.
Thanks in advance.
Well, you are partially right, BUT software is developed better when you split thing according of what they do...
The method Ausgabe have a job: display the result only
The method square have a job: do the math operation only
So the whole point behind soft development is not that the code works
we try to do something else:
it must work
it must be easy to maintain
it must be easy to improve
all those requirements are related to the project's complexity and can be reached based on a single responsibility principle
For something as trivial as i*i you wouldn't need a method. However if instead have to do a more complicated operation which would require quite a few lines of code, then it would be a good idea to put that in its own method in order to keep your code clean and easy to read, understand and maintain. Moreover if you need to do the same operation at multiple points in your program, then a method would be beneficial as you do not have to copy/paste the same code over and over again in different places.
I'm planning on creating a calculator for physics that would run off of a few equations. But, I realized that it would be a lot of code.
With the equation v = x/t (just one of many I want to include) , there's already three possible equations.
v = x/t x = vt t = x/v
What I was planning to have the program do is:
-Ask the user what equation they're going to use
-Ask what variable is missing
-Solve for it with a matching equation
My question is whether or not there is a way I can format the code more efficiently. Without knowing how, it seems like running a lot of very similar code for each variant of an equation.
I'm planning to create this using multiple classes, if it isn't clear.
There's 2 approaches I can think of that would make the most sense.
The first more traditional way would be to make a bunch of classes for each kind of equation you wanted to include.
public class Velocity implements Equation{
public double solveT(double v, double x){
if(v != 0)
return x / v;
else
return 0; //or whatever value is appropriate
}
public double solveX(double v, double t){
return v * t;
}
public double solveV(double t, double x){
if(t != 0)
return x / t;
else
return 0; //or whatever value is appropriate
}
}
This keeps all of your different equations separate, and if you define an empty Equation interface you can substitute different Equation objects as needed. The drawback is that you'd have a lot of classes to keep track of, and you would have to make sure that the Equation object you're trying to call methods on is the correct instance, i.e. trying to call solveX() on a Density instance that doesn't have a solveX() method. However, having each class separate is a nice way to organize and debug.
The other approach is using Java8 lambdas:
interface twoTermEq{
double solve(double a, double b);
}
public class Calculator{
public double solveTwoTermEq(twoTermEq eq, double a, double v){
eq.solve(a, b);
}
}
public static void main(String[] args){
twoTermEq velSolveX = (t, v) -> return t * v;
twoTermEq velSolveT = (x, v) -> v != 0.0 ? return x / v : 0.0;
twoTermEq velSolveV = (x, t) -> t != 0.0 ? return x / t : 0.0;
//define as many equations as needed...
Calculator c = new Calculator();
//select which equation to run, collect user input
....
//do the calculation
double result = c.solveTwoTermEq(velSolveX, t, v);
}
This lets you define your equations all in one place and doesn't need a boatload of classes. You could similarly define interfaces for ThreeTermEq, FourTermEq, etc., as well as solveThreeTermEq(), solveFourTermEq(), etc. methods for the Calculator class. The drawback here is that it might become more difficult to maintain and organize, and I believe there's an upper limit on how big a class file can be; if a class file becomes too big it won't compile, which could happen if you've defined tons of equations.
For me the choice would come down to how I wanted to organize the code; if I wanted to only include a (relatively) small number of (relatively) simple equations, I would probably use lambdas. If I wanted to include every physics equation across as many physics topics as possible, I'd probably use classes.
Either way, there's going to have to be some similar code written for different permutations of an equation - I don't think there's really any way around that. You could try for a novel approach using a bunch of Objects to try to circumvent that, but I think that would be overwrought and not worth the effort; it's not like flipping variables around is hard.
You would probably be best off using some kind of symbolic math toolbox. Maple and MatLab are good languages/environments for working with equations, as they recognize symbolic math and can manipulate equations fairly easily. Java does not have any built in libraries for this, and it is difficult to find any libraries that would support a 'Computer Algebra System' to manipulate the equations for you. You might want to look at JAS (Java Algebra System), but I'm not sure that will do what you're looking to do. Most likey, you will need to solve for each variable by hand and build functions for each individual expression.
If you're sticking with Java, this is how I would go about it. In terms of code formatting, I would just create one Equation class that holds an array of all the variations of a given equation. The variations (i.e. V=I*R, I=V/R, R=V/I) would all be passed into the constructor for the class. A solve method could then be implemented that takes the requested variable to be solved for, the other variables and their values (distinguished by two arrays- one for characters and one for values)
Usage could be as follows:
Equation ohmsLaw = new Equation(new String[] {"V=I*R", "I=V/R", "R=V/I"});
double resistance = ohmsLaw.solve('R', new char[] {'I', 'V'}, new double[] {0.5, 12.0});
You would need to write a little bit of symbolic parsing, but that makes it fun, right?
May or may not have been the answer you were looking for, but hopefully it's some help. Good luck!
I have the following code, please keep in mind I'm just starting to learn a language and a such have been looking for fairly simple exercises. Coding etiquette and critics welcome.
import java.util.*;
import java.io.*;
public class Tron
{
public static void main(String[] args) throws Exception
{
int x,z,y = 0;
File Tron= new File("C:\\Java\\wordtest.txt");
Scanner word = new Scanner(Tron);
HashMap<String, Integer> Collection = new HashMap<String, Integer>();
//noticed that hasNextLine and hasNext both work.....why one over the other?
while (word.hasNext())
{
String s = word.next();
Collection.get(s);
if (Collection.containsKey(s))
{
Integer n = Collection.get(s);
n = n+1;
Collection.put(s,n);
//why does n++ and n+1 give you different results
}else
{
Collection.put(s,1);
}
}
System.out.println(Collection);
}
}
Without the use of useDelimiter() I get my desired output based on the file I have:
Far = 2, ran = 4, Frog = 2, Far = 7, fast = 1, etc...
Inserting the useDelimiter method as follows
Scanner word = new Scanner(Bible);
word.useDelimiter("\\p{Punct} \\p{Space}");
provides the following output as it appears in the text file shown below.
the the the the the
frog frog
ran
ran ran ran
fast, fast fast
far, far, far far far far far
Why such a difference in output if useDelimiter was supposed to account for punctuation new lines etc? Probably pretty simple but again first shot at a program. Thanks in advance for any advice.
With word.useDelimiter("\\p{Punct} \\p{Space}") you are actually telling the scanner to look for delimiters consisting of a punctuation character followed by a space followed by another whitespace character. You probably wanted to have one (and only one) of these instead, which would be achieved by something like
word.useDelimiter("\\p{Punct}|\\p{Space}");
or at least one of these, which would look like
word.useDelimiter("[\\p{Punct}\\p{Space}]+");
Update
#Andrzej nicely answered the questions in your code comments (which I forgot about), however he missed one little detail which I would like to expand / put straight here.
why does n++ and n+1 give you different results
This obviously relates to the line
n = n+1;
and my hunch is that the alternative you tried was
n = n++;
which indeed gives confusing results (namely the end result is that n is not incremented).
The reason is that n++ (the postfix increment operator by its canonical name) increments the value of n but the result of the expression is the original value of n! So the correct way to use it is simply
n++;
the result of which is equivalent to n = n+1.
Here is a thread with code example which hopefully helps you understand better how these operators work.
Péter is right about the regex, you're matching a very specific sequence rather than a class of characters.
I can answer the questions from your source comments:
noticed that hasNextLine and hasNext both work.....why one over the other?
The Scanner class is declared to implement Iterator<String> (so that it can be used in any situation where you want some arbitrary thing that provides Strings). As such, since the Iterator interface declares a hasNext method, the Scanner needs to implement this with the exact same signature. On the other hand, hasNextLine is a method that the Scanner implements on its own volition.
It's not entirely unusual for a class which implements an interface to declare both a "generically-named" interface method and a more domain-specific method, which both do the same thing. (For example, you might want to implement a game-playing client as an Iterator<GameCommand> - in which case you'd have to declare hasNext, but might want to have a method called isGameUnfinished which did exactly the same thing.)
That said, the two methods aren't identical. hasNext returns true if the scanner has another token to return, whereas hasNextLine returns true if the scanner has another line of input to return.
I expect that if you run the scanner over a file which doesn't end in a newline, and consume all but one of the tokens, then hasNext would return true while hasNextLine would return false. (If the file ends in a newline then both methods will behave the same - as there are more tokens if and only if not all lines have been consumed - but they're not technically the same.)
why does n++ and n+1 give you different results
This is quite straightforward.
n + 1 simply returns a value that is one greater than the current value of n. Whereas n++ sets n to be one greater, and then returns that value.
So if n was currently 4, then both options would return 5; the difference is that the value of n would still be 4 if you called n + 1 but it would be 5 if you called n++.
In general, it's wise to avoid using the ++ operator except in situations where it's used as boilerplate (such as in for loops over an index). Taking two or three extra characters, or even an extra line, to express your intent more clearly and unambiguously is such a small price that it's almost always worth doing.
In the following line of code:
x = x.times(x).plus(y);
in what order are these expressions going to be executed?
Will it be like:
x = (x + y)*x
or x = (x^2) + y,
or something else and why?
Links to documentation about the specific subject will be highly appreciated as I had no luck with my search. Apparently I don't know where to look at and what to look for.
Thank you.
These are methods; the fact that they are called "plus" and "times" doesn't mean that they'll necessarily follow the behaviour of the built-in + and * operators.
So x.times(x) will be executed first. This will return a reference to an object, on which plus(y) will then be executed. The return value of this will then be assigned to x. It's equivalent to:
tmp = x.times(x);
x = tmp.plus(y);
Here's a link to a documentation which most likely contains the required answer (probably at 15.7). It's highly technical and verbose but not inaccessible to most people (I believe).
However, it seems that you're just starting programming, so you'll be better off reading other answers here, and programming more to get an intuitive feel (not exactly a 'feel', as it's systematic and rigourous) of the order of operations etc...
Don't be afraid to write "throw-away" code (which you can incidentally save too) to find out things you don't know if you don't know where else to look for the answer. You can always google more intensively or dive through the language specs at a latter date. You'll learn faster this way. :)
One simple way to find out is to write something like this:
class Number{
private int number;
public Number(int x){
number = x;
}
public Number times(Number x){
System.Out.PrintLn("times");
return number * x;
}
public Number plus(Number x){
System.Out.PrintLn("plus");
return number + x;
}
}
Method chains get executed from left to right, with each method using the result from the previous method, so it will be x = (x^2) + y.
What you're referring to in the algebraic expressions is operator precedence - evaluating multiplications before addition, for example. The Java compiler knows about these rules for expressions, and will generate code to evaluate them as you expect.
For method calling, there are no "special rules". When given x = x.times(x).plus(y); the compiler only knows that to evaluate x.times(x).plus(y), it first needs to know what x is, so it can call times on it. Likewise, it then needs to know what x.times(x) is so it can call the plus method on that result. Hence, this type of statement is parsed left to right : (x * x) + y.
Some languages allow the creation of functions that are "infix" with user supplied precedence. (such as Haskell : See http://www.haskell.org/tutorial/functions.html, section "Fixity declarations"). Java is, alas, not one of them.
It's going to be executed in left-to-right order, as
x = (x.times(x)).plus(y)
The other way:
x = x.(times(x).plus(y))
doesn't even make sense to me. You would have to rewrite it as
x = x.times(x.plus(y))
to make sense of it, but the fact that the second x is contained within times() while the y is outside it rules out that interpretation.
The reason the documentation doesn't say anything about this is probably that such expressions follow the normal rules for how a statement like a.b().c().d() is evaluated: from left to right. We start with a and call the function b() on it. Then, we call c() on the result of that call, and we call d() on the result of c(). Hence, x.times(x).plus(y) will first perform the multiplication, then the addition.