Java Primitives
Calculator.
public class AvgCalculator{
public static void main(String[] args) {
// numDouble: User's input is a string, will be changed into a double
// Double is used to allow user to input decimal numbers
double numDouble = 0;
double sum = 0;
// count = n (sample size to determine mean)
// Sample size is always a whole number (ex: 1, 2, etc.)
int count = 0;
double mean = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter numbers, type 'end' to finish");
while (true) {
// String is used as the input for each number
// The reason why I didn't use int was because I wanted the user to
// be able to end the calculator by typing "end"
System.out.println("Number: ");
String numStr = sc.next();
System.out.println(numStr);
if ("end".equals(numStr)) {
break;
}
// This performs casting by changing the input, which was a string,
// into a double so that the mean can by determined
numDouble = Double.parseDouble(numStr);
sum += numDouble;
count++;
}
mean = sum/count;
System.out.println("Show detailed info? y/n");
String detail = sc.next();
// Setting showDetail as true/false, this can be used in the future
// as a toggle. (If showDetail = true, show more detail, otherwise,
// only show the result)
// Also showDetail can only be yes/no, so it can be set as a boolean
System.out.println(detail);
boolean showDetail;
if ("y".equals(detail)) {
showDetail = true;
} else {
showDetail = false;
}
if (showDetail) {
System.out.println("Sum: " + sum);
System.out.println("Count: " + count);
}
System.out.println("Mean: " + mean);
}
}
AvgCalculator.main(null)
What I learned
Primitives include: int, double, boolean
String is not a primitive.
Code:
Integer: int a
Double: double a
Boolean: boolean a
String: String a
To enable input, make sure to import the Scanner lirbary: import java.util.Scanner;
Useful stuff learned while creating calculator:
if and while statements:
If the variable is an integer/double, you can use ==
If the variable is a string, you must use .equals
Example: "foo".equals(variableName)
public class test {
public static void main(String[] args) {
int x = 5;
System.out.println("This is an integer: " + x);
}
}
test.main(null)
import java.util.Scanner;
public class Scanning {
public static void main(String[] args) {
Scanner test = new Scanner(System.in);
System.out.println("Enter a number: ");
int input = test.nextInt();
System.out.println(input);
System.out.println("Your number is: " + input);
}
}
Scanning.main(null);