Conditional Statements and Operators

 

First Example


public class Main {
	
	public static void main(String[] args) {

		Scanner scan = new Scanner(System.in);	// Create and import scan object.
		
		System.out.println("Write Correct Answer!");
		System.out.print("32 + 24 = ");
		
		int answer = scan.nextInt(); // Allows us to enter values.

		//Basic if, else if, else;
		
		if(32 + 24 == answer) {	// Equal to : ==
			//Equal
			System.out.println("Correct Answer");
		}
		
		else if(32 + 24 > answer) {
			//Less
			System.out.println("Wrong Answer!");
		}
		
		else {			// Others 
			//Over
			System.out.println("Wrong Answer!");
		}
			
	}
	
}







Second Example

Basic calculator with JAVA :)


import java.util.Scanner;

public class Main {
	
	public static void main(String[] args) {
		
		float first, second;
		float result = 0f; // Initialize result.
		String operation;
		
		Scanner scan = new Scanner(System.in);
		
		System.out.print("Enter first number: ");
		first = scan.nextFloat();
		
		System.out.print("Enter second number: ");
		second = scan.nextFloat();
		
		
		System.out.print("Select operation(+, -, x, /): ");
		operation = scan.next();
		//operation.equals() It tells whether the value entered is equal to the operation. Return boolean;
		if(operation.equals("+")) {
			result = first + second;
		}
		
		else if(operation.equals("-")) {
			result = first - second;
		}
		
		else if(operation.equals("x")) {
			result = first * second;
		}
		
		else if(operation.equals("/")) {
			result = first / second;
		}
		
		System.out.println(result);
	
	}
	
}




Good Bye Everyone


Image resource: https://www.examtray.com/sites/default/files/2019-06/java-relational-operators-priority-chart.jpg

0 Comments