第四章 資料輸入
概述:比如注冊登錄時,填寫的用戶名,密碼之類的就是要輸入的資料
Scanner 使用的基本步驟:(注意大小寫,點,括號別忘了加)
1.導包
import java.util.Scanner; (固定寫法,不用變,此句要放在public class 之前)
2.創建物件
Scanner a = new Scanner(System.in); (除了變數名 a 可以改變,其他都不變)
3.接受資料
int i = a.nextInt(); (除了變數名 i 可以變,a是之前取的變數名,其他都不變)
樣式:
import java.util.Scanner; (導包)
public class shuju{
public static void main(String[] args){
Scanner a = new Scanner(System.in); (創建物件)
int i = a.nextInt(); (資料輸入)
System.out.println(i);
}
}
案例:三個和尚升級版
三個和尚,測量出他們的身高,然后輸出最高的值
import java.util.Scanner; (導包)
public class heshang{
public static void main(String[] args){
Scanner a = new Scanner(System.in); (創建物件)
System.out.println("請輸入第一和尚的身高"); (提示資訊)
int height1 = a.nextInt(); (輸入資料)
System.out.println("請輸入第二個和尚的身高");
int height2 = a.nextInt();
System.out.println("請輸入第三個和尚的身高");
int height3 = a.nextInt();
int tempheight = height1 > height2 ? height1 : height2; (三元運算子)
int maxheight = tempheight > height3 ? tempheight : height3;
System.out.println("最高身高為:" + maxheight + "cm");
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/283010.html
標籤:Java
上一篇:尼科徹斯定理
