輸入輸出
輸出
基本語法
System.out.println(msg); //輸出一個字符串,自帶換行 System.out.print(msg); //輸出一個字符串,不帶換行 System.out.printf(msg); //格式化輸出,和C語言相同
例如:
public class SannerDemo { public static void main(String[] args) { System.out.println("hello world!"); System.out.print("hello world!"); String str = "hello world"; System.out.printf("%s\n",str); } }
快捷鍵推薦:在這里,如果使用的是 IDEA的話,可以輸入sout然后回車,會自動輸出 System.out.println();
輸入
使用Scanner讀取
首先需要導入==import java.util.Scanner;==的包,然后 Scanner sc =new Scanner(System.in);,這段代碼的主要作用是,從鍵盤中輸入中讀取數據。
然后讀取數據:
next()、nextInt()和nextLIne()的區別;
import java.util.Scanner; public class SannerDemo { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int i = sc.nextInt(); System.out.println(i); //讀取int型的數據 //讀取一行數據 String s1 = sc.nextLine(); System.out.println(s1); //讀取字符串 String s2 = sc.next(); System.out.println(s2); }
nextInt():
int i = sc.nextInt(); System.out.println(i); //讀取int型的數據
可以讀取數字,但是遇到空格,只能讀取空格前的數字。
next():
// //讀取字符串 String s2 = sc.next(); System.out.println(s2);
可以讀取字符串,但是遇到空格,只能讀取空格前的數字。
nextLine():
//讀取一行數據 String s1 = sc.nextLine(); System.out.println(s1);
可以讀取字符串,并讀取這一行 ,但是遇到回車結束。
注意:
next()和nextLine()不可以同時使用:
例如:
//讀取字符串 String s2 = sc.next(); System.out.println(s2); //讀取一行數據 String s1 = sc.nextLine(); System.out.println(s1);
這樣只會輸出一行,這是因為nextLine()讀取了回車,然后結束。
next()遇到空客會結束。
使用Scanner循環讀取N個數字/字符串
hasNextInt()的使用
import java.util.Scanner; public class SannerDemo { public static void main(String[] args) { Scanner sc =new Scanner(System.in); while (sc.hasNextInt()){ int i = sc.nextInt();//輸入數字i System.out.println(i);//打印數字i } }
當程序開始之后,會一直循環輸入并打印一個數字,知道Ctrl+d結束程序
在這里sc.hasNextInt()的結果是一個boolean的類型,當結果為false是結束。
注意:
Ctrl+d用來結束循環輸入多個數據
同理:
這些方法都可以用于循環數據輸入。
關于Scanner中nextxxx()須注意的一點
public static void main(String[] args) { // TODO code application logic here Scanner s = new Scanner(System.in); //需要注意的是,如果在通過nextInt()讀取了整數后,再接著讀取字符串,讀出來的是回車換行:"\r\n",因為nextInt僅僅讀取數字信息,而不會讀走回車換行"\r\n". //所以,如果在業務上需要讀取了整數后,接著讀取字符串,那么就應該連續執行兩次nextLine(),第一次是取走整數,第二次才是讀取真正的字符串 int i = s.nextInt(); System.out.println("讀取的整數是"+ i); String rn = s.nextLine();//讀取到的是空格 String a = s.nextLine();//讀取到的是字符串 System.out.println("讀取的字符串是:"+a); }
PS:nextDouble,nextFloat與nextInt是一樣的
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/weixin_52142731/article/details/111870960