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");
Conocer a Java como lenguaje de programación
¿Qué es Java?
Versiones de Java y JDK
Las herramientas más usadas de Java
Creando un entorno de desarrollo en Java en Windows
Creando un entorno de desarrollo en Java en Mac
Creando un entorno de desarrollo en Java en Linux
Escribe tu primer Hola Mundo en Java
Etapas de la programación en Java
La JShell de Java
Trabajar con Variables en Java
Variables en Java
Actualizando variables
Convención de Nombres en Java
Técnica de Naming: Camel Case
Tipos de datos numéricos
Tipos de datos char y boolean
Operadores de Asignación, Incremento y Decremento
Operaciones matemáticas
Cast en variables: Estimación y Exactitud
Casteo entre tipos de datos
Archivos .JAR
¡A practicar!
Aplicar condicionales en Java
Sentencia if
Alcance de las variables y Sentencia ELSE
Operadores Lógicos y Expresiones booleanas
Sentencia Switch
Escribir funciones en Java
¿Para qué sirven las funciones?
Implementa Funciones en Java
Java Docs
Javadoc en funciones
Tags Java Docs
Analizar e implementar Ciclos en Java
Bucle do While
Operador Ternario y Bucle While
Bucle For
Break, Continue y Return
Arrays
Declarando Arreglos
Indices y búsqueda de elementos en Arrays
Ciclos For anidados
Continua con el Curso de Programación Orientada a Objetos en Java
No tienes acceso a esta clase
¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera
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 88
Preguntas 6
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");
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 😄
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.
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.
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. ✌️
Excelente Intro… 😉
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
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
String profe ="Anahí Salgado";
if(profe == "Anahí Salgado"){
System.out.println("Excelente curso");
}
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 😎🍷
La sentencia If es el pan nuestro de cada dia en la programacion.
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
<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");
}
}
}
Puede asignar el valor de una variable usando operadores ternarios:
variable = (condition) ? expressionTrue : expressionFalse;
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");
}
}
}
¡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 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);
}
}```
✨ La sentencia if permite que nuestra aplicación tome decisiones.
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
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");
}
}
}>
me encanta ese acento de misterio al iniciar jajjaja
Muy buen inicio de la clase. 😃
Entendido.
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
Todo clarísimo. Gracias
En que version esta corriendo?
Genial!!
muy bien
Todo muy claro
entendido
If una condicional que vale ORO …
excelente explicación ^^
Una clase muy bien explicada.
Nice
Buena introducción
Buenísimo el cambio de ritmo al inicio de esta clase 10/10
excelente curso, buena introduccion
if todo claro 😃
Super Claro!
public class SentenciaIf {
public static void main(String[] args) {
boolean validacion = true;
int contador = 0;
if (validacion) {
contador++;
System.out.println("Enviado");
}
}
}
Jajja, esa intro estuvo de pelicula !!
Las computadoras tambien toman decisiones, y esas decisiones rompen ♡
jaja, el intro se sintio muy matrix
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 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);
}
}
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");
}
Hice unas mejoras al código 😄
Output👇
Este sería mi código de la clase (NetBeans):
En los recursos creo que “filesSended” esta mal declarada. Tiene una “s” de mas que no esta en fileSended++;.
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
Además del if, se puede usar el else if , else y la sentencia switch.
Excelente clase de las sentencias IF
Excelente comienzo!
Me gustó la explicación con manzanas 🤣.
Muy buena explicacion
Y-y-yo… yo, elijo la la la la pera ( ._.) 🍐
if para poder comprobar ciertos comportamientos en nuestro código.
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);
}
}
}```
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.");
}
}
}
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);
}
}
}
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");
}
}
}
Me antojé de manzanas jaajaj
¿Quieres ver más aportes, preguntas y respuestas de la comunidad?