Java核心技術卷_5_输出输入

来源:互联网 发布:饶颖为啥不告了知乎 编辑:程序博客网 时间:2024/04/30 22:36
/* * 這個程序關於輸入輸出 * @version 1.01 2017-09-25 * @author 黃子涵 */package inputtest;import java.util.Scanner;public class InputTest {      public static void main(String[] args)      {          /*讀取輸入*/          //先構造一個Scanner對象;          Scanner in=new Scanner(System.in);          //要通過控制台進行輸入,首先要構造一個Scanner對象,並與“標準輸入流”System.in關聯;          //進行行輸入;          System.out.println("你叫什麼名字?");          String name=in.nextLine();          //進行整數輸入;          System.out.println("你今年多少歲?");          int age=in.nextInt();          //對結果進行拼接,顯示名字,並且進行歲數加一;          System.out.println("Hello,"+name+".next year,you'll be"+(age+1));          /*格式化輸出*/          double x=10000.0/3.0;          System.out.printf("%8.2f%", x);//可以用8個字符的寬度和小數點后兩個字符的精度打印x;          //每一個以%字符開始的格式說明符都用相應的參數替換;          //格式說明符尾部的轉換符將指指示被格式化的數值類型:f表示浮點數,s表示字符串,d表示十進制整數;          System.out.printf("Hello,%s.Next year,you'll be %d",name,age);          //在printf中,可以使用多個參數;          String message=String.format("Hello,%s.next year,you'll be %d",name,age);          //可以使用靜態的String.format方法創建一個格式化的字符串,而不打印輸出;          /*文件輸入與輸出*/          //要想對文件進行讀取,就需要一個用File對象構造一個Scanner對象;          Scanner in=new Scanner(new File("myfile.txt"));          //要想寫入文件,就需要構造一個PrintWriter對象;          PrintWriter out=new PrintWriter("myfile.txt");      }}
原创粉丝点击