How to avoid multiple ifs inside a form? - java

I think this counts for any other language as well, but I'm using Java for Android in this example here. I'm trying to validate a form, but it has multiple inputs.
if( !anuncio.getEstado().isEmpty() ){
if( !anuncio.getCategoria().isEmpty() ){
if( !anuncio.getTitulo().isEmpty() ){
if( !valor.isEmpty() && !valor.equals("0") ){
if( !anuncio.getTelefone().isEmpty() ){
if( !anuncio.getDescricao().isEmpty() ){
saveForm();
}else {
showErro("please fill the entire form");
}
}else {
showErro("please fill the entire form");
}
}else {
showErro("please fill the entire form");
}
}else {
showErro("please fill the entire form");
}
}else {
showErro("please fill the entire form");
}
}else {
showErro("please fill the entire form");
}
Is there any way or method to simplify this? Because let's say if it were 10 inputs, it would be a horrible code doing 10 ifs, you know? How do I simplify this?

In your case this would suffice:
if( !anuncio.getEstado().isEmpty()
&& !anuncio.getCategoria().isEmpty()
&& !anuncio.getTitulo().isEmpty()
&& !valor.isEmpty() && !valor.equals("0")
&& !anuncio.getTelefone().isEmpty()
&& !anuncio.getDescricao().isEmpty() ) {
safeForm();
} else {
showErro("please fill the entire form");
}
For more complex code you may i.e. want to count errors and show messages later if count > 0 etc.
PS also I believe you wanted to write "showError" not "showErro"

More elegant way to write it:
if(!containsEmptyText(anuncio.getEstado(), anuncio.getCategoria(), anuncio.getTitulo(),
valor, anuncio.getTelefone(), anuncio.getDescricao()) && !valor.equals("0") ){
saveForm();
}else
showErro("please fill the entire form");
private static boolean containsEmptyText(String... textArray){
for(String text : textArray)
if(text.isEmpty())
return true;
return false;
}

Related

how to remove from a list from a combo box

When trying to write the following code, it comes up with 3 errors. Syntax error on token 'else', insert 'assignmentoperator expression' to complete assignment and that cannot convert from string to boolean. This is for a combo box and when I choose from the combo box, I want to remove the other sites from a list. 'site' is a variable in main and c.site is a parameter in another agent. Can someone explain what to do.
if ( site ) {
if ( c.site.equals( "x" ) ) {
cavernIterator.remove();
continue;
}
}
else {
if ( c.site.equals( "y" ) ) {
cavernIterator.remove();
continue;
}
}
else {
if ( c.site.equals( "z" ) ) {
cavernIterator.remove();
continue;
}
}
else {
( c.site.equals( "a" ) ) {
cavernIterator.remove();
continue;
}
}
You can't have several else blocks for the same if. Each else block has to be attached to its own if:
if(a) {
...
} else {
if (b) {
...
}
else {
if (c) {
...
}
else {
...
}
}
}
Or, with a shorthand for all this, you can have a single-statement block inside the else, so it looks like this:
if (a) {
...
}
else if (b) {
...
}
else if (c) {
...
}
else {
...
}
This second one is nearly the same as the first, as it takes advantage of not having to wrap a statement block in braces if your statement block only has single statement, like this:
if (myCondition)
System.out.println("My condition passed");
else
System.out.println("My condition did not pass");
Else if should be written this way :
if (...) {
// Code here
} else if (...) {
// Code here
} else {
// Code here
}
Also your cases seem similar
String[] sites = {"x","y","z","a"};
boolean contains = Arrays.stream(sites).anyMatch(c.site::equals);
if (contains) {
cavernIterator.remove();
continue;
}
EDIT: Considering site is a string
String site = "x"; // Default value provided
String[] sites = {"x","y","z","a"};
boolean condition = site.equals(c.site) && Arrays.stream(sites).anyMatch(c.site::equals);
if (condition) {
cavernIterator.remove();
continue;
}
if ( site ) {
if ( c.site.equals( "x" ) ) {
}
}
equals
if(site && c.site.equals("x")){
}
And your last else is messed up.
Likely look on some Java tutorials because you write the least efficient way possible. This is your code in short:
if (site && (c.site.equals("x") || c.site.equals("y") || c.site.equals("z") || c.site.equals("a"))) {
cavernIterator.remove();
}

For loop to search through 2D array in Java returns NullPointerException

For a project at University, I have to create a game of Tic Tac Toe.
I have this for loop with if statements to search through the 2D array of 3x3 size, and return if it's either X or O (enum). That results in showing which side has won the game.
However, the problem I have is that if the 2D array is not complete, as in if all the 9 boxes are not filled with X or O, the method shows a NullPointerException.
Edit: I have to add that I require the empty grid to be null as few other unit tests assume grid[][] is initialized as null.
Error:
Exception in thread "main" java.lang.NullPointerException
at TicTacToeImplementation.whoHasWon(TicTacToeImplementation.java:80)
at ApplicationRunner.main(ApplicationRunner.java:24)
Code:
public enum Symbol {
X, O
}
private Symbol winner;
public Symbol whoHasWon() {
for (Symbol xORo : Symbol.values()) {
if ((grid[0][0].equals(xORo) &&
grid[0][1].equals(xORo) &&
grid[0][2].equals(xORo))) {
winner = xORo;
isGameOver = true;
break;
} else if ((grid[1][0].equals(xORo) &&
grid[1][1].equals(xORo) &&
grid[1][2].equals(xORo))) {
winner = xORo;
isGameOver = true;
break;}
else if { //Code carries on to account for all 8 different ways of winning
} else {
isGameOver = true;
}
}
return winner;
}
You can use multiple ways to ignore the "null" exception with an empty array.
The 1st way is to fill it with a different default symbol such as E. So when you initialize your arry at the beginning, instead of making it all empty and null, you can fill it with E's
for(int i=0;i<=2;i++){
for(int k=0;k<=2;k++){
grid[i][k] = "E";
}
}
Add this to beginning to fill it with E's first instead of nulls.
Another method is to find how to ignore the nulls using try or the following methods that can be found in this linkhttps://www.javacodegeeks.com/2012/06/avoid-null-pointer-exception-in-java.html:
I won't be going into it because I believe the 1st method is easier to use and implement. However, depending on your requirements for your assignment, I would look at both just to be sure.
Hope this helps, Good luck!
You can change the comparasion of String.The code may be like this ;
public Symbol whoHasWon() {
for (Symbol xORo : Symbol.values()) {
if ((grid[0][0] == xORo.name() &&
grid[0][1] == xORo.name() &&
grid[0][2] == xORo.name())) {
winner = xORo;
isGameOver = true;
break;
} else if ((grid[1][0] == xORo.name() &&
grid[1][1] == xORo.name() &&
grid[1][2] == xORo.name())) {
winner = xORo;
isGameOver = true;
break;}
else if { //Code carries on to account for all 8 different ways of winning
} else {
isGameOver = true;
}
}
return winner;
}
Enum like your's implemented
public enum Symbol{
X, O
}
}
As stated in this post, you can use either equals() or == to compare enums but using == is null safe while equals() isn't.
So basically, just write your checks like this:
if (grid[0][0] == xORo &&
grid[0][1] == xORo &&
// etc.
However, if you want to use the equals() method, you could just write a method that checks for null then compares the two values and returns the result:
public boolean isEqual(Symbol s1, Symbol s2) {
if (s1 != null && s1.equals(s2)) {
return true;
}
return false;
}
You could then call the isEqual() method like this:
if (isEqual(grid[0][0], xORo) &&
isEqual(grid[0][1], xORo) &&
// etc.

Printing a tree

I have written an ID3 and it prints the data. However, this is not very readable when the data sets become large. Is there any more human readable way this can be done?
Example of output given by the code below:
if( Outlook == "Sunny") {
if( Humidity == "High") {
PlayTennis = "No";
} else if( Humidity == "Normal") {
PlayTennis = "Yes";
}
} else if( Outlook == "Overcast") {
PlayTennis = "Yes";
} else if( Outlook == "Rain") {
if( Wind == "Weak") {
PlayTennis = "Yes";
} else if( Wind == "Strong") {
PlayTennis = "No";
}
}
I would ideally like to get a graph as follows from the above output:
Is there something I could use instead of these methods to give a tree automatically. The end goal is to analyse the tree depth etc?
Take a look at https://code.google.com/p/treelayout/
It is the layout code used by antlr and seems to work pretty well.

Tic Tac Toe, checking legal move

New to the site and have not been coding long. I am trying to find a way to check to see if the entered value is withing the array range as well as checking to see if the position is already occupied. I am running into trouble if the problems are not in order. I would like for it to catch the problem in any order and request them to enter another value, then recheck again. Thanks for any advice!
This is what I ended up doing. Any thoughts? Thanks again.
//in play game method
while(checkNotInBounds(move)){
System.out.println("Out of Bounds! Please try again...");
move = getMove(player);
}
while(!checkSpaceFree(move, boardValues)){
System.out.println("Space Taken! Please try again...");
move = getMove(player);
while(checkNotInBounds(move)){
System.out.println("Out of Bounds! Please try again...");
move = getMove(player);
}
//Method: checkInBounds
//Purpose: find out if move is in bounds
public static boolean checkNotInBounds(int[] move){
if(move[0] > 2 || move[0] < 0 || move[1] > 2 || move[1] < 0){
return true;}
return false;
}
//Method: checkFreeSpace
//Purpose: find if space is free
public static boolean checkSpaceFree(int[] move, char[][]boardValues){
if(boardValues[move[0]][move[1]] == ' '){
return true;}
return false;
}
Why not split it up into two methods instead of one as your trying to do two things there and switching isn't neccary then
do something like
public static boolean checkLegalMove(int[] move, char[][] boardValues){
if(move[0] > 2 || move[0] < 0 || move[1] > 2 || move[1] < 0){
return false;
}
if(boardValues[move[0]][move[1]] != ' '){
return false;
}
return true;
}
public void doSomething(boolean checkLegalMove(move,boardValues), char player){
boolean check = checkLegalMove(move,boardValues);
char temp = player;
if(check ==true ){
//do something to player
}else{
getMove(player);
}
}

Android EditText validation

I have two EditText like editText1 and editText2.
I am taking input from EditText to name1 and name2.
Now I want to validate that the EditText are not empty before clicking on ok button.
For this I used:
if(editText1==NULL && editText2==NULL) {
textView.setText("please enter Names");
} else {
other code;
}
But its not validating, and with empty EditText it is showing result on clicking ok button.
I have also tried in this way:
if(name1==NULL && name2==NULL) {
textView.setText("please enter Names");
} else {
other code;
}
What to do?
Try this:
if(editText1.getText().toString().trim().equals("")
&& editText2.getText().toString().trim().equals(""))
{
textView.setText("Please enter Names");
}
else
{
// other code
}
Please use:
if(name1.compareTo("") == 0 || name2.compareTo("") == 0) {
// Your piece of code for example
Toast toast=Toast.makeText(getApplicationContext(), "ENTER NAMES", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
} else {
// Your code
}
This will work definitely for sure.
Try like this name1.equals("") in place of name1==NULL
if(name1.equals("") && name2.equals(""))
{
textView.setText("please enter Names");
}
else
{
other code;
}
if(name1.compareTo("") == 0 || name2.compareTo("") == 0)
{
// Your piece of code for example
}
you can use:
if(name.compareTo("") == 0 || name.compareTo(null) == 0) {}
This works very well for me, try this
if(editText1.getText().toString().length == 0 && editText2.getText().toString().length == 0)
{
textView.setText("Please enter names");
}
else
{
//some other actions to perform
}
if(editText1.getText().toString().length() > 0 && editText2.getText().toString().length() > 0)
{
textView.setText("Please enter Names");
}
else
{
// Other code
}

Categories