On Day 2 of 30 days of Java, I learned about Scanner for getting user input.
Java Scanner class:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter Name");
String name = scan.nextLine(); // Read user input
System.out.println("Name is: " + name); // Output user input
int age = scan.nextInt(); // Read user input
System.out.println("Age is: " + age); // Output user input
}
}
Reading user input:
In the above example, nextLine() has been used to read a string input. For other data types:
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user
nextLine() Trap:
**Trap: Putting nextLine() ahead of nextInt(), nextDouble(), nextLong(), or next().
Solution: add a throwaway nextLine() before the real nextLine() other wise nextLine() will not skip the whitespace (delimiter).
Comparison Operators in Java:
Java Switch Statements
int month = 2;
switch(month) {
case 1:
System.out.println("Jan");
break;
case 2:
System.out.println("Feb");
break;
default:
System.out.println("Mar");
}
// Outputs "Feb" (month 2)
Functions in Java
Functions in Java have the following structure:
<access_modifier> <return_type> <method_name>( list_of_parameters)
{
//body
}
class Main {
public static void main(String[] args) {
int numberOfPeople = countPeople(12, 15);
public int countPeople(int group1, int group2){
int people = group1+group2;
return people;
}
}
}
where
access_modifier can be public, private,...
return_type can be void, int, String,...
method_name can be sth like countPeople,...
parameters' type should be declared (int num1, int num2)