This question already has answers here:
What is a Question Mark "?" and Colon ":" Operator Used for? [duplicate]
(7 answers)
Closed 7 years ago.
I have these two methods. I understand the "getTotalSalary" one but don't really get the way in which "getAverageSalary" is written. I don't understand why the question mark and colon is used as well as the "(size() != 0)" and 0 at the end.
This is the coding:
public double getTotalSalary() {
double total = 0;
for (Employee e : empReg) {
total = total + e.getSalary();
}
return total;
}
public double getAverageSalary() {
return (size() != 0) ? this.getTotalSalary() / this.size() : 0;
}
empReg is the name of the ArrayList. Employee is a class which consists of "name" and "salary". getSalary is obviously a method returning the salary.
The question mark is called the ternary operator, and it is used to make a decision based on an evaluation. It is often used to replace if statements, since they do the same thing. For example, an if statement with that would be written:
if (size != 0)
return this.getTotalSalary() / this.size();
else
return 0;
In my experience, I only use it if I want to reduce the code size. However, it does make the code a bit more difficult to read.
You cannot divide by zero.
? and : is a ternary operator. It means that if the expression before ? is true, then this.getTotalSalary() / this.size()will be returned, otherwise return 0.
It's called ternary operator in java, here you have some examples: http://alvinalexander.com/java/edu/pj/pj010018
See this discussion: What is a Question Mark "?" and Colon ":" Operator Used for?
It explains
A traditional if-else construct in C, Java and JavaScript is written:
if (a > b) {
result = x;
} else {
result = y;
}
This can be rewritten as the following statement:
result = a > b ? x : y;
Related
This question already has answers here:
How Do I Print the values in a recursive Program in Java?
(5 answers)
Closed 2 years ago.
java write recursive function that accept int : k and print to screen k of "*"
Attempt:
public static String numStarec(int k) {
String ans = "";
if (k == 0) {
ans += "*";
return ans;
}
return numStarec(k-1);
}
this code not work and print for me only "*" ones I know the problem
I tried to fix that but , unfortunately without successes
Example :
k = 3
console : ***
You can append an asterisk after each recursive call, with the base case returning an empty string when k is 0.
public static String numStarec(int k) {
if(k == 0) return "";
return numStarec(k-1) + "*";
}
Demo
Before writing the solution to the problem, I think it would be valuable for you to understand the definition of recursion and what is it that you want to happen. First things first, "recursion is a method of solving a problem where the solution depends on solutions to smaller instances of the same problem" (Source).
If the previous definition still confuses you a bit then lets take a look at the solution to your problem:
public static String numStarec(int k) {
if (k == 0) {
return "";
}
return numStarec(k-1) + "*";
}
As the definition says, "method of solving a problem..." (In this specific case the problem you have is that you want to print the character * an amount K of times on screen) "...where the solution depends on solutions to smaller instances of the same problem" (Where these smaller instances of the same problem consist on finding out how many characters '*' are left to be printed, which is what the value of K is for)
What is happening when you provide the function numStarec with a certain number K is that it will take K and check whether it is 0 or not. If K == 0 evaluates to true then the return statement will be "" but while K != 0 evaluates to true, what will happen is that the function will return the character "*" and keep on invoking itself with the value of K-1 and once again return accordingly.
Hope it helps you understand a little bit about recursion.
This question already has answers here:
What is the Java ?: operator called and what does it do?
(17 answers)
Closed 7 years ago.
Two questions about using a question mark "?" and colon ":" operator within the parentheses of a print function: What do they do? Also, does anyone know the standard term for them or where I can find more information on their use? I've read that they are similar to an 'if' 'else' statement.
int row = 10;
int column;
while (row >= 1)
{
column = 1;
while(column <= 10)
{
System.out.print(row % 2 == 1 ? "<" : "\r>");
++column;
}
--row;
System.out.println();
}
This is the ternary conditional operator, which can be used anywhere, not just the print statement. It's sometimes just called "the ternary operator", but it's not the only ternary operator, just the most common one.
Here's a good example from Wikipedia demonstrating how it works:
A traditional if-else construct in C, Java and JavaScript is written:
if (a > b) {
result = x;
} else {
result = y;
}
This can be rewritten as the following statement:
result = a > b ? x : y;
Basically it takes the form:
boolean statement ? true result : false result;
So if the boolean statement is true, you get the first part, and if it's false you get the second one.
Try these if that still doesn't make sense:
System.out.println(true ? "true!" : "false.");
System.out.println(false ? "true!" : "false.");
Thats an if/else statement equilavent to
if(row % 2 == 1){
System.out.print("<");
}else{
System.out.print("\r>");
}
a=1;
b=2;
x=3;
y=4;
answer = a > b ? x : y;
answer=4 since the condition is false it takes y value.
A question mark (?)
. The value to use if the condition is true
A colon (:)
. The value to use if the condition is false
Also just though I'd post the answer to another related question I had,
a = x ? : y;
Is equivalent to:
a = x ? x : y;
If x is false or null then the value of y is taken.
Maybe It can be perfect example for Android,
For example:
void setWaitScreen(boolean set) {
findViewById(R.id.screen_main).setVisibility(
set ? View.GONE : View.VISIBLE);
findViewById(R.id.screen_wait).setVisibility(
set ? View.VISIBLE : View.GONE);
}
They are called the ternary operator since they are the only one in Java.
The difference to the if...else construct is, that they return something, and this something can be anything:
int k = a > b ? 7 : 8;
String s = (foobar.isEmpty ()) ? "empty" : foobar.toString ();
it is a ternary operator and in simple english it states "if row%2 is equal to 1 then return < else return /r"
This question already has answers here:
What is a Question Mark "?" and Colon ":" Operator Used for? [duplicate]
(7 answers)
Closed 8 years ago.
Could someone give me a detailed explanation of what's going on here; I'm getting confused by the ?:
for (int i = 0; i < datasize; i++) {
String data1value = data1.size() > i ? data1.get(i) : null;
String data2value = data2.size() > i ? data2.get(i) : null;
String data3value = data3.size() > i ? data3.get(i) : null;
The ternary operator is being used to prevent getting an IndexOutOfBoundsException here. If the size of the Collection is > than current index i, it assigns that value through get(i), otherwise it assigns null.
If you had assigned the values directly as
String data1value = data1.get(i);
your code could break if the loop runs for more than the number of items in the Collection.
The ? : operator in Java is an expression which returns one of two values.
In Java you might write
if (a > b) {
max = a;
}
else {
max = b;
}
Setting a single variable to one of two states based on a single condition is such a common use of if-else that a shortcut has been devised for it, the conditional operator, ?:. Using the conditional operator you can rewrite the above example in a single line like this:
max = (a > b) ? a : b;
They are used be the reason presented in the response from Ravi Thapliyal.
This question already has answers here:
What is the Java ?: operator called and what does it do?
(17 answers)
Closed 8 years ago.
I've been trying to Google it, but googling the key "?" doesn't really work out that good.
I really want to know what it does and when to use it.
Thanks!
I've seen it a couple times, but here is an example of one I just saw
String name = perms.calculateRank().getColor() + player.getName();
//This is a custom ranking system ^
player.setPlayerListName(name.length() > 15 ? name.substring(0, 16) : name);
player.setDisplayName(name + ChatColor.RESET);
Chat.sendMessage(player, "Tab Name Set");
This is a ternary operator. In Java specifically, it is called the Conditional Operator. It is a way of writing short-hand simple if..else statements. For example:
if (a == b) {
c = 123;
} else {
c = 456;
}
is the same as:
c = a == b ? 123 : 456;
It is also used for a wildcard generic.
public List<?> getBizarreList();
The ternary operator someBoolean ? x : y evaluates to x if someBoolean is true, and y otherwise.
It is called ternary operator and it is only operator that takes 3 operands. In better sense, it is conditional operator that represent shorter format
General Syntax :
boolean expression ? value1 : value2
your example:
player.setPlayerListName(name.length() > 15 ? name.substring(0, 16) : name);
as same as
if( name.length() > 15)
player.setPlayerListName(name.substring(0, 16));
else
player.setPlayerListName(name);
This question already has answers here:
What is the Java ?: operator called and what does it do?
(17 answers)
Closed 7 years ago.
Two questions about using a question mark "?" and colon ":" operator within the parentheses of a print function: What do they do? Also, does anyone know the standard term for them or where I can find more information on their use? I've read that they are similar to an 'if' 'else' statement.
int row = 10;
int column;
while (row >= 1)
{
column = 1;
while(column <= 10)
{
System.out.print(row % 2 == 1 ? "<" : "\r>");
++column;
}
--row;
System.out.println();
}
This is the ternary conditional operator, which can be used anywhere, not just the print statement. It's sometimes just called "the ternary operator", but it's not the only ternary operator, just the most common one.
Here's a good example from Wikipedia demonstrating how it works:
A traditional if-else construct in C, Java and JavaScript is written:
if (a > b) {
result = x;
} else {
result = y;
}
This can be rewritten as the following statement:
result = a > b ? x : y;
Basically it takes the form:
boolean statement ? true result : false result;
So if the boolean statement is true, you get the first part, and if it's false you get the second one.
Try these if that still doesn't make sense:
System.out.println(true ? "true!" : "false.");
System.out.println(false ? "true!" : "false.");
Thats an if/else statement equilavent to
if(row % 2 == 1){
System.out.print("<");
}else{
System.out.print("\r>");
}
a=1;
b=2;
x=3;
y=4;
answer = a > b ? x : y;
answer=4 since the condition is false it takes y value.
A question mark (?)
. The value to use if the condition is true
A colon (:)
. The value to use if the condition is false
Also just though I'd post the answer to another related question I had,
a = x ? : y;
Is equivalent to:
a = x ? x : y;
If x is false or null then the value of y is taken.
Maybe It can be perfect example for Android,
For example:
void setWaitScreen(boolean set) {
findViewById(R.id.screen_main).setVisibility(
set ? View.GONE : View.VISIBLE);
findViewById(R.id.screen_wait).setVisibility(
set ? View.VISIBLE : View.GONE);
}
They are called the ternary operator since they are the only one in Java.
The difference to the if...else construct is, that they return something, and this something can be anything:
int k = a > b ? 7 : 8;
String s = (foobar.isEmpty ()) ? "empty" : foobar.toString ();
it is a ternary operator and in simple english it states "if row%2 is equal to 1 then return < else return /r"