Scanner
从键盘导入 :
1.包
import java.util.Scanner;
2.实例化
Scanner s = new Scanner(System.in);
3.调用
int num = s.nextInt()
练习:
Scanner s = new Scanner(System.in);
System.out.println("age(int):");
int num = s.nextInt();
System.out.println(num);
System.out.println("name(string):");
String name = s.next();
System.out.println(name);
System.out.println("report(double):");
double report = s.nextDouble();
System.out.println(report);
System.out.println("yes?(boolean):");
boolean anser = s.nextBoolean();
System.out.println(anser);
System.out.println("char(1):");
String chars = s.next();
char charss = chars.charAt(1);//1 索引
System.out.println(charss);
if else结构:
System.out.print(report+ ":" );
if (report <60){
System.out.println("不及格");
}
else if( report>= 60 && report<75){
System.out.println("及格");
}
else if( report>=75 && report<85){
System.out.println("良");
}
else if( report>=85 && report<=100){
System.out.println("优");
}
else{
System.out.println("成绩有误");
}
if-else 的类似结构 switch-case 结构(S-C结构不能表示范围):
Scanner scan = new Scanner(System.in);
String season = scan.next();
switch(season)
{
case "Spring" :
System.out.println("春");
break;
case "Summer" :
System.out.println("夏");
break;
case "autumn" :
System.out.println("秋");
break;
default:
System.out.println("冬");
}
for循环
int sum = 0;
int count = 0;
for(int i =100;i > 1;i--)
{
if(i%2 ==0 ){
System.out.print(i+" ");
sum += i;
count ++;
}
}
System.out.println();
System.out.println("总和:"+sum);
System.out.println("个数:"+count);
之前学习的总和测试:家庭账单
在这里插入代码片package welcome_java;
import java.util.Scanner;
public class FamilyAccount {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
boolean isFlag = true;
double countMoney = 0.0;
double money = 0.0;
String details = "收/支 金额 账户金额 备注\n";
String proform = "";
while(isFlag) {
System.out.println("-------家庭账单-------");
System.out.println("1.明细");
System.out.println("2.收入");
System.out.println("3.支出");
System.out.println("4.退出");
System.out.println("-------家庭账单-------");
int flag = scan.nextInt();
switch (flag) {
case 1:
System.out.println("--------收支明细--------");
System.out.println(details);
System.out.println("--------收支明细--------");
break;
case 2:
System.out.println("收入金额:");
money = scan.nextDouble();
countMoney += money;
System.out.println("备注");
proform = scan.next();
details += "收入\t\t" + money + "\t\t" + countMoney + "\t\t" + proform + "\n";
System.out.println("----记录成功----");
break;
case 3:
System.out.println("支出金额:");
money = scan.nextDouble();
countMoney -= money;
System.out.println("备注");
proform = scan.next();
details += "支出\t\t" + money + "\t\t" + countMoney + "\t\t" + proform + "\n";
System.out.println("----记录成功----");
break;
case 4:
System.out.println("确定退出?(Y/N):");
String outFlag = scan.next();
if (outFlag.equals("Y") || outFlag.equals("y")) {
// 退不出去 因为比较的是地址 if(outFlag == "Y"){
isFlag = false;
break;
}
default:
System.out.println("输入有误重新输入");
}
}
}
}