之前一直不知道JAVA怎麼輸入…正好報名的雲課堂開課了,根據預習視頻發現了輸入方式。囧~
給Scanner來作一些處理.
Scanner類中提供了多個方法:
next():取得一個字符串;
nextInt():將取得的字符串轉換成int類型的整數;
nextFloat():將取得的字符串轉換成float型;
nextBoolean():將取得的字符串轉換成boolean型;
用Scanner獲得用戶的輸入非常的方便,但是Scanner取得輸入的依據是空格符,包括空格鍵,Tab鍵和Enter鍵.當按下這其中的任一鍵時,Scanner就會返回下一個輸入. 當你輸入的內容中間包括空格時,顯然,使用Scanner就不能完整的獲得你輸入的字符串.這時候我們可以考慮使用BufferedReader類取得輸入.
輸入方式代碼
import java.util.Scanner;
public class FieldTest
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int x, sum = 0;
System.out.print("請輸入整數:");
x = in.nextInt();
while (x != -1)
{
sum += x;
x = in.nextInt();
}
System.out.print("請輸入string字符:");// string
String s = in.next();
System.out.println(s);
System.out.print("請輸入char字符:");
// 不可用char s2 = in.next();
String s2 = in.next();
char s3 = s2.charAt(0);// 注意char型的輸入方式
System.out.println(s3);
System.out.println("整數和爲:" + sum);
}
}
運行結果
請輸入整數:1 2 3 -1
請輸入string字符:ILOVEYOU
ILOVEYOU
請輸入char字符:ILOVEYOU
I
整數和爲:6
數組代碼
import java.util.Scanner;
public class FieldTest
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int x, sum = 0, cnt = 0;
int[] numbers = new int[100];
System.out.print("請輸入整數:");
x = in.nextInt();
while (x != -1)
{
numbers[cnt] = x;
sum += x;
cnt++;
x = in.nextInt();
}
int i;
for (i = 0; i < cnt; i++)//也可以i < numbers.length,且更好
{
System.out.print(numbers[i] + " ");
}
System.out.println("\n整數和爲:" + sum);
}
}
運行結果
請輸入整數:1 2 3 4 5 6 -1
1 2 3 4 5 6
整數和爲:21