一: if else 语句练习:
Scanner scanner = new Scanner(System.in);
System.out.print("Number: ");
int num = scanner.nextInt();
if (num %5 0 && num%30)
System.out.println(“FizzBuzz”);
else if (num%5==0)
System.out.println(“Fizz”);
else if (num % 3 ==0)
System.out.println(“Buzz”);
else
System.out.println(num);
二:while 循环练习:
String input = “”;
Scanner scanner = new Scanner(System.in);
while (true){
System.out.println(“input :”);
input = scanner.next().toLowerCase();
if (input.equals(“pass”))
continue;
if (input.equals(“quit”))
break;
System.out.println(input);
}
三: for each 循环
String[] fruits = {“apple”,“banana”,“peach”};
for (String fruit: fruits)
System.out.println(fruit);
限制:只能从左往右,不能从后往前
无法访问每一个item 的索引,只有一个循环变量
四:添加错误处理的抵押额计算器
public class Main {
public static void main(String[] args) {
byte month = 12;
byte percent = 100;
Scanner scanner = new Scanner(System.in);
int principal = 0;
float rate_month = 0;
while (true) {
System.out.print("Principal:($1K - $1W) ");
principal = scanner.nextInt();
if (principal >= 1000 && principal <= 1000000)
break;
System.out.println("enter a number between 1000 and 1,000,000.");
}
while (true) {
System.out.print("Annual Interest Rate: ");
rate_month = scanner.nextFloat() / month / percent;
if (rate_month >= 0 && rate_month <= 30)
break;
System.out.println("enter a value greater than 0 and less than 30 ");
}
System.out.print("Period (Year): ");
byte period = scanner.nextByte();
double res = principal * (rate_month * (Math.pow(1 + rate_month, period * month)) / (Math.pow(1 + rate_month, period * month) - 1));
String res1 = NumberFormat.getCurrencyInstance().format(res);
System.out.print("mortgage: " + res1);
}
主函数太过繁杂,需要进一步简化