No tienes acceso a esta clase

¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera

Adquiere por un año todos los cursos, escuelas y certificados por un precio especial.

Antes: $249

Currency
$219/año

Paga en 4 cuotas sin intereses

Paga en 4 cuotas sin intereses
Comprar ahora

Termina en:

1D
19H
32M
56S
Curso de Introducción a Java SE

Curso de Introducción a Java SE

Anahí Salgado Díaz de la Vega

Anahí Salgado Díaz de la Vega

Sentencia if

22/39
Recursos

Los condicionales son la forma en que las computadoras toman decisiones, evaluaran si la condición para ejecutar una parte del código se cumple. Si el resultado de la operación es verdadero ejecutarán esta parte del código, en caso de que no, seguirán con las siguientes instrucciones.

La forma de programar condicionales es usando la sentencia IF (hay más, pero las veremos más adelante) de la siguiente manera:

if (condición) {
  // instrucciones
}

En el siguiente ejemplo vamos a guardar algunas instrucciones dentro del condicional IF, Java solo ejecutará esta parte del código si se cumple la condición, en este caso, que la variable isBluetoothEnabled sea igual a true:

boolean isBluetoothEnabled = true; // también podría ser false
int filesSended = 3;

if (isBluetoothEnabled) {
  fileSended++;
  System.out.println("Archivo enviado");
}

Aportes 92

Preguntas 6

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad?

o inicia sesión.


boolean tiempo = true;
    boolean energia = true;
    
    if(tiempo && energia){
      System.out.println("Pues ponte a estudiar el Curso de Introducción a Java SE con Anahí Salgado en Platzi");

Sentencia if
.
Condicionales: son la manera en la que una maquina toma decisiones a la hora de ejecutar el código. Funciona de modo “falso” o “verdadero”.
.
Algunos operadores que puedes ocupar
&& es el operador condicional “AND”
|| es el operador condicional “OR”
?: es el operador ternario
Instanceof es el operador instanceof
.
Articulo referente a distintos operadores 😃
http://www.manualweb.net/java/operadores-condicionales-java/

Booleanos de Java
Muy a menudo, en la programación, necesitará un tipo de datos que solo puede tener uno de dos valores, como:

  • SI NO

  • ENCENDIDO APAGADO

  • VERDADERO FALSO
    Para esto, Java tiene un tipo de datos boolean, que puede tomar los valores true o false.

No es por nada, pero que buena es Ann enseñando 😄

jejeje mi aporte

int fileSent*
As verbs the difference between sended and sent
is that sended is (nonstandard) (send) while sent is (send).

The past tense of the word “send” is “sent.”
I’m just nitpicking over here.

Solo comentario, la palabra Sended no existe en inglés. Se dice Sent. Muy buen contenido ciertamente y que bueno que enseñas desde el inicio buenas prácticas descritas en libros de Clean Code.

la verde, las de agua son mas sabrosas 😄

Manzana verde! con queso

If en sóla línea ?? por su puesto que es posible con un operador ternario.
Sintaxis:
condicion? expresion1: expresion2;
Explicación:
Se evaluda la condicion, sí es verdadera devuelve la expresion1 y sí es falsa devuelve la expresion2.
Ejemplo:

Llama bastante la atención el inicio de la clase que fue bien explicada y si me preguntan a mi, buscaría la forma de obtener ambas manzanas.

Ya me adelante jaja

public class Condicional {
    public static void main(String[] args) {
        boolean Bluetooth = true;
        int Archivo = 0;
        if (Bluetooth)
        {
            Archivo++;
            if(Archivo == 1)
            {
                System.out.println(Archivo + " Archivo enviado");
            }else
            {
                System.out.println(Archivo + " Archivos enviados");
            }
        }else
        {
            System.out.println("No hay conexión");
        }
    }
}

Le puse un condicional adentro para que, si es un solo archivo no dijera “1 archivos enviados” sino en singular. Y una respuesta en caso de que sea false. ✌️

Una observación, el pasado del verbo send, es sent.
Me encantó la toma inicial

es increíble como me costo tantísimo la clase de programación básica y esta me esta resultando en comparación mas fácil

Excelente Intro… 😉

Este fue el inicio mas Matrix que he visto en la vida:

me encanta ese acento de misterio al iniciar jajjaja

JAJAJJJAJ
Adoro a esta maestra, me saco de onda el comienzo de la clase, esto no se ve en otro lado.
P.D: Manzana roja uwu

<code> public class IfState {
    public static void main(String[] args) {
        boolean isBluetoodEnable= true;
        int fileSend=2;

        if(isBluetoodEnable==true){
            fileSend++;
            System.out.println("Archivo enviado");
        } else {
            System.out.println("Archivo no enviado");
        }
    }
}

I’m ahead of my time 😎:

import java.lang.*;
import java.util.Scanner;

/**
 * IfPractice
 */

/**
 * basic structure of an if
 * if (condition) {
 *  //instructions
 * }
 */
public class IfPractice {

    public static void main(String[] args) {
        boolean bluetoothEnabled = false;
        //Boolean sendFile = null;
        int filesSended = 0;

        Scanner scanner = new Scanner(System.in);

        //mental note: == compares (for ex:) string objects, not their content
        //however, this does: if (myString.equals("text")) { //do something }

        //simulate wifi
        System.out.printf("Simulate wifi status (on/off): ");
        String bluetoothSimulation = scanner.next();

        if (bluetoothSimulation.equals("on") || bluetoothSimulation.equals("ON")) {
            bluetoothEnabled = true;
            System.out.println(bluetoothEnabled);
        } else if (bluetoothSimulation.equals("off") || bluetoothSimulation.equals("OFF")) {
            bluetoothEnabled = false;
            System.out.println(bluetoothEnabled);
        } else {
            //keeps it on false
            bluetoothEnabled = false;
        }

        System.out.printf("\n----//----//----\nDo you want to send a file? (y/n): ");
        char uAnswer = scanner.next().charAt(0);
        if (uAnswer == 'y' || uAnswer == 'Y') {
            System.out.printf("\n🗃----File-Sender----🗃\n\n");
            if (bluetoothEnabled == true) {
                try {
                    //send a file
                    //let user choose file
                    System.out.printf("Name of the file: ");
                    String fileName = scanner.next();
                    Thread.sleep(100);
                    System.out.printf("Name of the reciever: ");
                    String recieverName = scanner.next();
                    Thread.sleep(1000);
                    System.out.printf("\nSending file(s) to %s... 📄\n", recieverName);

                    Thread.sleep(1500);
                    filesSended++;
                    System.out.printf("File sent: %s\nTotal of files sent: %d🔥\n", fileName, filesSended);
                } catch (InterruptedException e) {
                    //TODO: handle exception
                    ;
                }
            } else if (bluetoothEnabled == false) {
                System.out.printf("\nTo share files you need to have a bluetooth connection\nand this is mandatory\n\n");
                try {
                    System.out.printf("Do you want to turn on the bluetooth? (y/n): ");
                    char uAnswerBluetooth = scanner.next().charAt(0);
                    if (uAnswerBluetooth == 'y') {
                        System.out.printf("Turning on the bluetooth...\n");
                        Thread.sleep(1000);
                        System.out.println("Bluetooth is on! run this program again 😎🍷");
                    } else if (uAnswerBluetooth == 'n') {
                        System.out.printf("\nOkay, glad to helped!\nc ya later 😎\n");
                    } else {
                        System.out.printf("\nERROR: the only two valid answers are 'y' & 'n',\nhowever you entered %c (❌)\n\n", uAnswerBluetooth);
                        System.exit(1);
                    }
                } catch (InterruptedException e1) {
                    //TODO: handle exception
                }
            } else {
                ; //booleans have only two states
            }

        } else if (uAnswer == 'n' || uAnswer == 'N') {
            System.out.printf("\nOkay, glad to helped!\nc ya later 😎\n");
            System.exit(0);
        } else {
            System.out.printf("\nERROR: the only two valid answers are 'y' & 'n',\nhowever you entered %c (❌)\n\n", uAnswer);
            System.exit(1);
        }

    }
}

Samples Output: possible case #1

Simulate wifi status (on/off): on 
true

----//----//----
Do you want to send a file? (y/n): y

🗃----File-Sender----🗃

Name of the file: test_1.txt
Name of the reciever: @kdav_5758

Sending file(s) to @kdav_5758... 📄
File sent: test_1.txt
Total of files sent: 1🔥

Samples Output: possible case #2

Simulate wifi status (on/off): off
false

----//----//----
Do you want to send a file? (y/n): y

🗃----File-Sender----🗃


To share files you need to have a bluetooth connection
and this is mandatory

Do you want to turn on the bluetooth? (y/n): y
Turning on the bluetooth...
Bluetooth is on! run this program again 😎🍷
public class ifStatement {
    public static void main(String[] args) {
        boolean isBluetoothEnable = true;
        int fileSended = 0;

        if(isBluetoothEnable){
            //Send file
            fileSended++;
            System.out.println("Archivo enviado");
        }
        //Cantidad de archivos enviados
        System.out.println(fileSended);

    }
}```

¡Hola!
Estuve experimentando con las condiciones switch y if, y este es mi código por si lo quieren examinar 😃

public class Terms {
    public static void main(String[] args) {
        int isOk = 3; //1 true, 0 false

        //Switch
        switch (isOk){
            case 0:
                System.out.println("False");
                break;
            case 1:
                System.out.println("True");
                break;
            default:
                System.out.println("I don't know it :c");
                break;
        }

        //If else
        if (isOk == 0){
            System.out.println("False");
        }
        else if (isOk == 1){
            System.out.println("True");
        }
        else{
            System.out.println("I don't know it :(");
        }
    }
}

Le halle mas comodidad a if, ya que con switch no pude trabajar con datos de tipo booleano 🙂

public class Ejercicio3 {
    public static void main(String[] args) {
        boolean isBluetoothEnable = true;
        int fileSended = 3;

        if(isBluetoothEnable){
            fileSended++;
            System.out.println("Archivo #"+fileSended+" enviado correctamente");
        }
    }
}

Apuntes de clase

public static void main(String[] args) {
boolean isBluethoothEnabled = true;
int fileSended = 3;

 if (isBluethoothEnabled){
     //Send file
     fileSended++;
     System.out.println("Archivo Enviado");

Posdata: me dio ganas de hacer algo como de apocalipsis zombie 😂 jajajajaja

public class ConditionalIf {
    public static void main(String[] args) {
        //check if the bluetooth system is ON
        boolean bluetoothEnable = true;
        //How many file are you loaded?
        int filesLoaded = 2;
        //If it's true so  load a file

        if(bluetoothEnable){
            filesLoaded ++;
            System.out.println("THE FILE HAS BEEN SUCCESS LOADED");
            System.out.println( "You have loaded: " + filesLoaded);
        }
    }
}

It is not too much, but it’s honestly work haha

String profe ="Anahí Salgado";
        
      if(profe == "Anahí Salgado"){
          
          System.out.println("Excelente curso");
      }
public class If {
    public static void main(String[] args) {

        String fruit = "apple";
        if (fruit=="apple"){
            System.out.println("The fruit is an apple");
        }
        else {
            System.out.println("The fruit is not an apple");
        }
    }
}

Comparto un ejercicio que realice con la condicion if anidada

 Scanner hora = new Scanner(System.in);
        int opcion;

        System.out.println("Que hora es ");
        opcion = hora.nextInt();

        if (opcion == 6 && opcion <= 12){
            System.out.println(" Buenos dias ");
        } else if (opcion >= 13 && opcion == 20){
            System.out.println(" Buenas tardes ");
        } else if (opcion <= 21 || opcion == 24 && opcion <= 5){
            System.out.println(" Buenas noches");
        } else {
            System.out.println(" No es una hora correcta ");
        }
<public class ifStatement {
    public static void main(String[] args) {
        boolean isBluetoothEnabled = true;
        int fileSended = 3;

        if (isBluetoothEnabled){
            //Send file
            fileSended++;
            System.out.println("Archivo Enviado");
        }
    }
}> 

La estructura condicional más simple en Java es el if, se evalúa una condición y en caso de que se cumpla se ejecuta el contenido entre las llaves {} o en caso de que se omitan se ejecuta el código hasta el primer «;»
https://programandoointentandolo.com/2017/07/estructuras-condicionales-java.html#:~:text=La estructura condicional más simple,la siguiente instrucción al if.

Puede asignar el valor de una variable usando operadores ternarios:

variable = (condition) ? expressionTrue :  expressionFalse;

✨ La sentencia if permite que nuestra aplicación tome decisiones.

La sentencia If es el pan nuestro de cada dia en la programacion.

public class IfStatement {
    public static void main(String[] args) {
        boolean isBluetoothEnabled = true;
        int fileSent = 3;
        System.out.println(fileSent); //3

        if (isBluetoothEnabled) {
            //Send file
            fileSent++;
            System.out.println("Archivo enviado");
        }
       
        System.out.println(fileSent); //4
    }
}

public class SentenciaIf {
public static void main(String[] args) {
int edad = 17;
boolean boleta = true;

    if(edad >=18 && boleta){
        System.out.println("Bienvenido");
    }
    else
    if(edad >=18 && boleta == false){
        System.out.println("No puede entrar al concierto");
    }
    else
        System.out.println("No puede entrar es menor de edad");
    
}

}

Aquí mi aporte basado en los conocimientos que tengo en otros lenguajes😁:

int notaDelExamen = 10;

        if(notaDelExamen <= 4) {
            System.out.println("REPROBASTES");
        } else if (notaDelExamen == 5) {
            System.out.println("REFUERZAS");
        } else if(notaDelExamen >= 6 && notaDelExamen == 10) {
            System.out.println("APROBASTE");
        } else {
            System.out.println("AL PARECER NO PRESENTASTE EL EXAMEN");
        }

public static void main(String[] args) {
boolean yacomi = true;
int arroz = 2;
if (yacomi) {
// manda mensaje
arroz++;
System.out.println(" si ya comio");
System.out.println(arroz);
}
}

Este sería mi código de la clase (NetBeans):

jaja, el intro se sintio muy matrix

En los recursos creo que “filesSended” esta mal declarada. Tiene una “s” de mas que no esta en fileSended++;.

Las computadoras tambien toman decisiones, y esas decisiones rompen ♡

Jajja, esa intro estuvo de pelicula !!

Tablas de verdad

  • Esta clase es oro puro y de gran ayuda en condicionales

https://www.youtube.com/watch?v=Pfyuv5ZnNNw

  • Los condicionales son la forma en que las computadoras forman decisiones, evaluaran si la condición para ejecutar una parte del código se cumple. Si el resultado de la operación es verdadero ejecutarán esta parte del código, en caso de que no, seguirán con las siguientes instrucciones.
  • La forma de programar condicionales es usando la sentencia if (hay más, pero se verán más adelante).
  • Las computadoras también toman decisiones.

Escelente explicación de los ifs

Hasta acá sencillo

Amo la Intro, es como una escena de inicio de temporada de una serie, toda filosóficamente misteriosa

muy bien explicado

Una clase muy bien explicada.

public class SentenciaIf {
    public static void main(String[] args) {
        
        boolean validacion = true;
        int contador = 0;

        if (validacion) {
            contador++;
            System.out.println("Enviado");
        }
    }
}

Además del if, se puede usar el else if , else y la sentencia switch.

excelente explicación ^^

Genial!!

Buena introducción

Todo muy claro

muy bien

Nice

En que version esta corriendo?

Entendido.

Excelente clase de las sentencias IF

Excelente comienzo!

Muy buen inicio de la clase. 😃

entendido

If una condicional que vale ORO …

Buenísimo el cambio de ritmo al inicio de esta clase 10/10

excelente curso, buena introduccion

if todo claro 😃

Super Claro!

Todo clarísimo. Gracias

Me gustó la explicación con manzanas 🤣.

las condiciones en if siempre seran verdaderas, es por eso que cuando se cambio el boleano al false no arrojo un resultado:

sin embargo es posible hacer un if falso igualando la conficion a false como se muestra en la siguiente imagen

Me gustan mucho las condicionales ultimamente las estoy entendiendo mejor y eso me motiva

package CL_22;

public class SentencaIf {

    public static void main (String [] args){
        //declaracion de booleano
        boolean isBluetoothEnabled = true;
        int fileSended = 3;
        String file = "archivo subido";

        //declaracin de sentemcia if
        if (isBluetoothEnabled){
            fileSended++;
            System.out.println(file);
            System.out.println(fileSended);

        }

    }
}

Me antojé de manzanas jaajaj

public class IfState {
    public static void main(String[] args) {
        boolean isBluetoodEnable= true;
        int fileSend=2;

        if(isBluetoodEnable==true){
            fileSend++;
            System.out.println("Archivo enviado");
        } else {
            System.out.println("Archivo no enviado");
        }
    }
}

Andaba jugueteando un poco con el ejemplo que dio la profesora:

public class IfStatement 
{
    public static void main(String[] args) 
		{
        boolean isBluetoothEnabled = true;
        int fileSended = 3;

        if (isBluetoothEnabled == true)
        {
            System.out.println("Enviando archivo...");
            fileSended++;
            System.out.println("¡Archivo enviado!");
            System.out.println("Total de archivos enviados: " + fileSended);
        }
        else if (isBluetoothEnabled == false)
        {
            System.out.println("Al parecer su configuracion Bluetooth esta desactivada...");
            System.out.println("Por favor verifique la configuracion de esta.");
        }
        else
        {
            System.out.println("Hubo un error desconocido.");
        }
    }
}

Y-y-yo… yo, elijo la la la la pera ( ._.) 🍐


muy clara la explicación de la condicional.

public class IfStatement {
    public static void main(String[] args) {
        boolean bluetoothActivo = true;
        int fileSendsed = 0;

        if(bluetoothActivo){
            fileSendsed ++;
            System.out.println("Archivo enviado ");
            System.out.println(fileSendsed);
        }
    }
}```

Muy buena explicacion

if para poder comprobar ciertos comportamientos en nuestro código.