Learn Java - Exercise 02y - Read Keyboard Characters

preview_player
Показать описание

Рекомендации по теме
Комментарии
Автор

2:15
He means that it doesn't matter what you initialize them as, true or false doesn't matter but it is important that you initialize them to something so that the program works and doesn't give error "sunny and warm are not initialized".

Don't ask how I know!

joeroganpodfantasy
Автор

Conditional with if-else-then statement :

char input1;
char input2;

System.out.println("Is it Sunny outside? (Y or N and press ENTER) ");
input1 = (char) System.in.read();

// For clearing buffer
input2 = (char)System.in.read();

System.out.println("Is it warm outside? (Y or N and press ENTER) ");
input2 = (char) System.in.read();

if (input1 == 'Y' && input2 == 'Y')
{
System.out.println("It is sunny and warm outside");
} else if (input1 == 'Y' && input2 == 'N')
{
System.out.println("It is sunny and cold outside");
} else if (input1 == 'N' && input2 == 'Y')
{
System.out.println("It is cloudy and warm outside");
} else if (input1 == 'N' && input2 == 'N')
{
System.out.println("It is cloudy and cold outside");
}

MrMpeder
Автор

The best Java tutorial so far. Thanks a lot Sir. You just made me hate to love Java!

AshrafulIslam-orbu
Автор

public static void main(String[] args)
throws java.io.IOException {

char input;
String var1 = "$", var2 ="$";

System.out.println("Is it sunny outside? (Enter Y or N)");
input = (char) System.in.read();

if(input == 'Y' || input == 'y' ) var1 = "sunny";
if(input == 'N' || input == 'n') var1 = "cloudy";

input = (char) System.in.read();
input = (char) System.in.read();

System.out.println("Is it warm outside? (Enter Y or N)");

input = (char) System.in.read();

if(input == 'Y' || input == 'y') var2 = "warm";
if(input == 'N' || input == 'n') var2 = "cold";

System.out.println("It is " + var1 + " and " + var2 + " outside");
}

ulradeja
Автор

Looking back at this exercise using boolean seems kind of redundant here cause we are already using logical operator and Y & N, so it feels like we are using boolean two times for no reason.
The yes no construct and using the logical operators we have already created a virtual boolean, just use that .


public static void main(String[] args)
throws java.io.IOException{
char input, input1, input2;

System.out.println("Is it sunny outside? (Enter Y or N)");
input = (char)System.in.read();

input1= input;

input = (char)System.in.read(); // clearing the buffer

System.out.println("Is it warm outside? (Enter Y or N)");
input = (char)System.in.read();

input2 = input;

if(input1 =='Y' && input2 =='Y')
System.out.println("It is sunny and warm outside.");

if(input1 =='Y' && input2 =='N')
System.out.println("It is sunny and cold outside.");

if(input1 =='N' && input2 =='Y')
System.out.println("It is cloudy and warm outside.");

if(input1 =='N' && input2 =='N')
System.out.println("It is cloudy and cold outside.");
}

joeroganpodfantasy