java的輸入輸出


0x01:輸出流

java常用的輸出語句有下面三種:

  1. System.out.println( );//換行打印,輸出之后會自動換行
  2.  System.out.print( );//不換行打印
  3. System.out.printf( );//按格式輸出

0x02:輸出示例

public class test {

    public static void main(String []args){
    
    System.out.println(1111);//換行打印,輸出后自動換行
    System.out.print(1111);//不換行打印
    System.out.printf("分數是:%d",88);//按格式輸出

    }
}

 

另外,System.out.printf如果報錯:

The method printf(String, Object[]) in the type PrintStream is not applicable for the arguments (String, int)

 

錯誤是和JDK的本版相關,具體的原因是Java Compiler中Compiler comlicance level的數值太低。將Compiler comlicance level設置為不小於1.5,重新建立工程即可。

方法:Project >> Properties >> Java Compiler >> Compiler comlicance level。

 

0x03:輸入流

java的輸入需要依賴Scanner類:

 import java.util.Scanner;

 

如果需要輸入,則先聲明一個Scanner對象:

Scanner s = new Scanner(System.in);

 

Scanner附屬於輸入流System.in,聲明Scanner對象之后,在輸入的時候需要使用next()方法系列指定輸入的類型,如輸入整數、輸入字符串等。

常用的next()方法系列:       nextInt():輸入整數    nextLine():輸入字符串     nextDouble():輸入雙精度數     next():輸入字符串(以空格作為分隔符)。

0x04:輸入示例

import java.util.Scanner;

public class test {

    Scanner s = new Scanner(System.in);  // 聲明Scanner的一個對象
System.out.print(
"請輸入名字:"); String name = s.nextLine(); System.out.println(name); System.out.print("請輸入年齡:"); int age = s.nextInt(); System.out.println(age); System.out.print("請輸入體重:"); double weight = s.nextDouble(); System.out.println(weight); System.out.print("請輸入學校:") String school = s.next(); System.out.println(school); s.close(); // 關閉輸入流,若沒有關閉則會出現警告 } }

輸出如下:

請輸入名字:梁 十 安
梁 十 安
請輸入年齡:18
18
請輸入體重:70.5
70.5
請輸入學校:xxx大學 阿斯頓
xxx大學

 

通過輸出,我們可以看到nextLine與next的區別

參考文章:https://blog.csdn.net/baidu_41666198/article/details/79942661

***************不積跬步無以至千里***************


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM