java 在控制台輸入


 

步驟:

(1)創建Scanner對象,接受從控制台輸入

Scanner input=new Scanner(System.in);
(2)接受String類型或int類型

String str=new input.next();
int n=input.nextInt();
  /*在新增一個Scanner對象時需要一個System.in對象,因為實際上還是System.in在取得用戶輸入。Scanner的next()方法用以取得用戶輸入的字符串;nextInt()將取得的輸入字符串轉換為整數類型;同樣,nextFloat()轉換成浮點型;nextBoolean()轉換成布爾型。*/

/*

其實next()與nextLine()區別很明確:

next() 方法遇見第一個有效字符(非空格,非換行符)時,開始掃描,當遇見第一個分隔符或結束符(空格或換行符)時,結束掃描,獲取掃描到的內容,即獲得第一個掃描到的不含空格、換行符的單個字符串。

使用nextLine()時,則可以掃描到一行內容並作為一個字符串而被獲取到。

*/

例:

(1)輸入一個字符串或數

import java.util.Scanner;

public class Demo59 {
public static void main(String[] args) {
//創建Scanner對象,接受從控制台輸入
Scanner input=new Scanner(System.in);
//接受String類型
String str=input.next();
//輸出結果
System.out.println(str);
}

}
 

(2)連續輸入多行數,以空行結束

public static void inputInteger() {
Scanner scanner = new Scanner(System.in);
String nextLine = scanner.nextLine();
int sum = 0;

while (nextLine != null && !nextLine.equals("")) {
sum += Integer.parseInt(nextLine);
System.out.println(sum);
nextLine = scanner.nextLine();
}

System.out.println("end of input integer");
}
(3)連續輸入多行字符串,以空行結束

public static void main(String[] args)
{
StringBuilder stringbuilder = new StringBuilder();
Scanner scanner = new Scanner(System.in);
while(true)
{
String text = scanner.nextLine().trim();
if ("".equals(text))
{
break;
}
stringbuilder.append(text);
}

System.out.println(stringbuilder.toString());
}
注:trim用於去除字符串兩端Unicode編碼小於等於32(\u0020)的所有字符;還可使用trim()的重載方法String.Trim(Char[])自定義需去除的符號。

(4)輸入多個數值,以空格分開

public static void inputIntInLine() {
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
String[] numstr = str.split(" ");
int[] nums = new int[numstr.length];
for(int i = 0; i < numstr.length; i ++) {
nums[i] = Integer.parseInt(numstr[i]);
}
for(int n: nums) {
System.out.println(n);
}
System.out.println("end of input int in a line");

}
(5)做題時可以正確的輸入

import java.util.Scanner;

public class Main{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
while(in.hasNext()){
String str = in.nextLine();
System.out.println(str);
}
}
}
 
————————————————
版權聲明:本文為CSDN博主「m0_37934678」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/m0_37934678/article/details/89015922


免責聲明!

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



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