读取输入字符串的方法:
通过Scanner类读取字符串的方法next()和nextLine()
import java.util.*;
public class Main{
public static void main(String []args){
Scanner scanner = new Scanner(System.in);
String a =scanner.next();//输入 ab cd ef
String b =scanner.nextLine();//输入 ab cd ef
System.out.println(a);//输出 ab
System.out.println(b);//输出 ab cd ef
}
}
next():一定要读取到有效字符后才可以结束输入,对输入有效字符之前遇到的空格键、Tab键或Enter键等结束符,next()方法会自动将其去掉,只有在输入有效字符之后,next()方法才将其后输入的空格键、Tab键或Enter键等视为分隔符或结束符。
nextLine():结束符只是Enter键,即nextLine()方法返回的是Enter键之前的所有字符,它是可以得到带空格的字符串的。
通过BufferReader类读取字符串
import java.io.*;
public class Main{
public static void main(String []args) throws IOException{
BufferReader buffer = new BufferReader(new InputStreamReader(System.in));
String a = buffer.nextLine();//输入 ab cd ef
System.out.println(a);//输出 ab cd ef
}
}
读取单个字符
public class Main{
public static void main(String []args){
Scanner scanner = new Scanner(System.in);
char a = scanner.next().charAt(0);
char b = (char)System.in.read();
}
}
字符串转化字符数组
public class Main{
public static void main(String []args){
Scanner scanner = new Scanner(System.in);
String a = scanner.nextLine();
char str[] = a.toCharArray();
}
}
字符数组转化字符串
import java.io.*;
public class Main{
public static void main(String []args) throws IOException{
String[] str = {"abc", "bcd", "def"};
StringBuffer sb = new StringBuffer();
for(int i = 0; i < str.length; i++){
sb. append(str[i]);
}
String s = sb.toString();
}
}
字符串变成整型数组
import java.util.*;
public class Main{
public static void main(String []args){
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();//1,2,3,4,5,6,7
String str1[] = str.split(",");
int [] number = new int[str.length];
for(int i=0;i