Android Studio if statement with OR (||) Function - java

I am creating a mobile application that updates users with the current score and final score in a football match. I want the textview displaying the score to show only the current or final score.
I am having trouble with the if statement. I need one of the fields to contains something in order for a record to be created so I have:
if (!(et_currentgoals.getText().toString().isEmpty()) || !(et_finalgoals.getText().toString().isEmpty()){
}
Inside this if statement I was another that updates the textview with the correct values. So if the final number of goals was entered, the current goals are discarded. Would the best way be something like this:
if(!(et_finalgoals.getText().toString.isEmpty()){
tv_goals.setText(et_finalgoals.getText().toString();
}else{
tv_goals.setText(et_currentgoals.getText().toString();
}
Does this cover both scenarios or am I missing something?

Having that second if block inside the first will work, but there's a simpler way.
This single if will work.
if (!et_finalgoals.getText().toString.isEmpty()) {
tv_goals.setText(et_finalgoals.getText().toString();
} else if (!et_currentgoals.getText().toString.isEmpty()) {
tv_goals.setText(et_currentgoals.getText().toString();
}
In other words, these two blocks are equivalent
if (a || b) {
if (a) {
// a
} else {
// b
}
}
if (a) {
// a
} else if (b) {
// b
}
If I'm understanding correctly, you are executing additional code inside of that first if statement, after setting the tv_goals text. To do that now, you can just check the text of tv_goals.
if (!tv_goals.getText().toString.isEmpty()) {
// Do additional code
}
If this is the case, it ends up being the same amount of code as your original solution. You should just pick whichever way is more clear to you.

Related

How do I switch between two views being visible?

I am making an application that helps score a table tennis game. I am at the final stages but I am having trouble with switching the server around every two points. I have given it a lot of thought but I can only get it to switch once. I know it is probably an easy solution but it's just not coming to me.
Here's how I am switching it once. I am using a count each time the button is pressed and when it reaches a number divisible by 2 it switches to the right.. However, using this logic is making it difficult to switch back! Thanks in advance.
public void serveSwitch() {
TextView leftServe = findViewById(R.id.leftServe);
TextView rightServe = findViewById(R.id.rightServe);
serverCount++;
if (server.serve=="left") {
if (serverCount % 2 == 0) {
rightServe.setVisibility(View.VISIBLE);
leftServe.setVisibility(View.GONE);
}
}
The part I'm struggling with is the logic on how to switch visibility every two points
If I get your point right, you want to toggle the visibility from off to on every two points and vice versa
You can do something like:
...
if (server.serve=="left") {
if (serverCount % 2 == 0) {
switch (rightServe.getVisibility()) {
case View.GONE:
rightServe.setVisibility(View.VISIBLE);
break;
case View.VISIBLE:
rightServe.setVisibility(View.GONE);
break;
}
switch (leftServe.getVisibility()) {
case View.GONE:
leftServe.setVisibility(View.VISIBLE);
break;
case View.VISIBLE:
leftServe.setVisibility(View.GONE);
break;
}
}
}
Note: I left the equality as-is as you say there is no problem with it. but in general you should use .equals() when it comes to compare strings in java.

Android Studio If statement with || and && operator

I'm creating an application which updates users on the score of a football match either in real time or as a final result. At least one score must be inputted in order for the TextView to be updated and the relevant score to be displayed. I'm checking that at least 1 of a pair of EditText fields is not empty using the following code:
if(!(et_current.getText().toString().isEmpty())||(!(et_final.getText().toString().isEmpty()))
&& (!(et_current2.getText().toString().isEmpty())||(!(et_final2.getText().toString().isEmpty()))){
if(!(et_final.getText().toString().isEmpty()))
tv_final.setText(et_final.getText().toString());
else
tv_current.setText(et_current.getText().toString());
if(!(et_final2.getText().toString().isEmpty()))
tv_final2.setText(et_final2.getText().toString());
else
tv_current2.setText(et_current2.getText().toString());
}
I want to be able to set the correct TextView so I have another if statement inside the original if statement to see ensure the correct score is being updated.
When I run the code, I do not seem to be getting past the first if statement. Am I using the correct format or is there an better way to complete these checks?
Thanks!
For readabilities sake, get some variables going
boolean currentEmpty = et_current.getText().toString().isEmpty();
boolean current2Empty = et_current2.getText().toString().isEmpty();
boolean finalEmpty = et_final.getText().toString().isEmpty();
boolean final2Empty = et_final2.getText().toString().isEmpty();
And then your code can be much cleaner. Something like
if( (!currentEmpty || !finalEmpty) || (!current2Empty || !final2Empty)) {
if(finalEmpty) {
tv_current.setText(et_current.getText());
}
else {
tv_final.setText(et_final.getText());
}
if(final2Empty) {
tv_current2.setText(et_current2.getText());
}
else {
tv_final2.setText(et_final2.getText());
}
}
I'm not sure if that is completely correct as the requirement is not entirely clear to me, but it should atleast be a good start to follow what's going on.

Java help regarding looping (do loops)

I'm trying to make a very basic game where you guess a number between 1-1000 using a do loop. Everything works, except when I finally make the correct guess, I am still prompted to make another guess, and when I enter the same correct guess again, the program terminates like it's suppose to.
Why do I have to make that extra guess to finally get my program to work? Am I looping around an extra time? Also, if I make a correct guess (the compiler will say I am correct then still prompt me), then a wrong guess (the compiler will tell me I'm wrong), then the correct guess again, the program will only terminate after I make the correct guess a second time.
The second do loop at the bottom is what I put in my main method. Everything above is in a method I wrote called play.
public static boolean play()
{
boolean c;
int n = 0;
do {
String input = JOptionPane.showInputDialog("Enter a number between 1-1000");
n = Integer.parseInt(input);
if (n == guess)
{
System.out.println("Correct");
c = true;
}
else if (n < guess)
{
System.out.println("Not Right");
c = false;
}
else
{
System.out.println("Not Right");
c = false;
}
guess++;
} while (c == false);
return c;
}
In main method:
do {
game1.play();
} while (game1.play() != true);
This loop runs the play method twice in each iteration of the loop :
do {
game1.play(); // first call
} while (game1.play()!=true); // second call
You are not testing the value returned by the first call, so even if it returns true, you would still call game1.play() again, which will display "Enter a number between 1-1000" again.
Replace it with:
boolean done = false;
do {
done = game1.play();
} while (!done);
This would only call play() one time in each iteration of the loop.
That said, I'm not sure why you need the outer loop.
You can just replace in with one call to game1.play(), since game1.play() will loop until the correct number is entered.

If, else if, else

Let's say that I have two strings that can be passed as parameter:
String one = "one";
String two = "two";
Which of the following methods would be the most efficiƫnt?
private void exampleOne(String example){
if(example.equals("one"){
// do this
}else{
// do this
}
}
private void exampleTwo(String example){
if(example.equals("one"){
//do this
}else if(example.equals("two"){
// do this
}
}
private void exampleThree(String example){
if(example.equals("one"){
// do this
}
if(example.equals("two"){
// do this
}
}
I would compare the methods for efficiency, if they have the same functionality. Currently, all the 3 methods are functionally different. So, no point is there in comparing them.
exampleOne() - If example is equal to "one", execute if. Execute else for all other values.
exampleTwo() - If example is equal to "one", execute if. Execute else if, if it is equal to "two", else for all other values, do nothing - (Here's one difference).
exampleThree() - Well, this one (as it stands) is more or less same as the 1st one, with one extra comparison, which btw, isn't going to affect much as far as efficiency is concerned. However, there are chances that both the if statements might execute in this method, if in between the two if statements, you assign string "two" to example, which is not possible in exampleOne method. To be more clear, you have two independent if blocks here, while in the first method, it's an if-else block (only one of which will be executed).
The one that, statistically speaking, makes the fewest string compares i.e.
if (example.equals("one"){
// do this
} else {
// do this
}
No one is the most efficient due that you have just two options, you should consider that the value doesn't be not one and not two, maybe other one (empty? null?) SO you should write something like that:
if(example.equals("one"){
//do this 1
}else if(example.equals("two"){
// do this 2
}else{
// do this 3
}
Those blocs can not be compared ans you can not state what is the best of them as they flow is different for each case.
This bloc provide two paths a positive and not.
private void exampleOne(String example){
if("one".equals(example){ //deciosn
// path positive
}else{
// path negative
}
}
This block provide three paths, positive, negative-positive, negative-negative
private void exampleTwo(String example){
if("one".equals(example){
//path positive
}else {
// path negative
if("two".equals(example{
// path negative-positive
}
}
}
This block provide four path, postive, negative and positive negative.
private void exampleThree(String example){
if("pne".equals(example){
// path positive
}
if("two".equals(example){
// path positive
}
}
As you see you have four different piece of code that you should not compare to state what is more efficient.
You should focus on the algorithm behind instead not how do the look.
Tip:
Try to use constant on the left side of compare, so you would avoid problems like dereferences and invalid assign.
I would say the first one, just because it only has to evaluate one expression every time...
In my opinion the second one because there you have direct control on both scenarios. When Sring is "one" and "two".
In exampleOne, the method doens't care if "two" or "three" is passed. It cares only situation if "one" is passed
The first one. Because you don't have to check other condition. In other you to make more operation.
The most efficient: 1, 2, 3.
But If you will have to check if i==0 and you will expect that most of them will be != better write if (i != 0) {} else{} than If (i==0) {...}
Keep everything as simple as possible
I'd say first, because if it just says else with no condition then it won't have to check anything, just go straight into 'else'
Theoretically, the first is most efficient.
Practically, you should go for the second, as it offers better readability and maintainability.
Remember, premature optimization is the root of all evil :)
1) most efficient, but this isn't good for maintainability.
private void exampleOne(String example){
if(example.equals("one"){
// do this
}else{
// do this
}
}
2) second efficient, but it is good for maintainability.
private void exampleTwo(String example){
if(example.equals("one"){
//do this
}else if(example.equals("two"){
// do this
}
}
3) third efficient.
private void exampleThree(String example){
if(example.equals("one"){
// do this
}
if(example.equals("two"){
// do this
}
}
i dont know what are your needs so, here you have mi opinions,
the first one, will ALLWAYS do only one checking.. so in that particular example it will be the one with less COMPARISONS.
the second ONE, will do at worst 2 comparisons 1 for "one" and 1 for "two" but... (there is allways a but) it will not any any job if the string is lets say "three" (in the first example it will go to the else)
the 3 example will do ALWAYS 2 COMPARISONS un less you put returns inside the ifs.
so, my opinion is there is not enough information to say wich one is more optimal.
one adition: you can try, instead of writing endles if... to use a case like this one:
switch (true) {
case example.equals("one"):
break;
case example.equals("two"):
break;
default:
break;
}
Apparently the first method would be the most efficient one compared with the possible values of parameters , since the additional if condition in the other methods is useless and will have nothing to do in your case. (extra condition check ==> lower efficiency)

How do I make JAVA perform an action based on MySQL data

I would like to make a java code that has different outcomes that are determined by data inside of a MySQL column. I have everything set up and I can connect to the database and view data. I don't know how I would use "If" with a mysql column.
Here is my code:
http://pastebin.com/UsJC7Qzx
What I'm trying to do specifically: I want to make the code print "Thanks for voting" if the MySQL column "given" is equal to 0 and then it will set the column to 1. And if the column is equal to 1 it will say "Thanks again for voting."
This is just a simple base for a voting reward system I'm doing for my video game.
If you don't have very good understanding of what I am trying to say read my notes inside of the code.
It would look something like this:
while (given.next()) {
if (given.getInt("given") > 0) {
System.out.println("Thanks again for voting");
} else {
System.out.println("Thanks for voting");
}
}
Would recommend that you rename the given resultset to something like say 'resultSet'.
I think you're almost there. Just need a couple of more lines.
st.executeQuery(give); returns a ResultSet. If you are guaranteed that your query will only return one result, you could simply do
ResultSet result = st.executeQuery(give);
if ( result.next() ) { // advances the resultset to the first result.
int actualVal = given.getInt('given');
if ( actualVal == 0 ) {
System.out.println("Thanks for voting");
// do the update here
st.executeUpdate("update has_voted set given = 1 where ...........");
}
else
System.out.println("Thanks again for voting");
}

Categories