Scanner读取字符串:
输入的是一行字符串:[I love you loveyou] Iloveyou
import java.util.Scanner;
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
s=s.replace('[',' ').replace(']',' '); //将输入的字符串中的 [ ] 替换掉, replaceAll 将匹配到的字符替换成新的字符
String[] chars = s.split("\\s"); //按空格将字符串划分存储在字符串数组中 或者 String[] chars = s.split(" ");
int n = chars.length-1;
String str = chars[n];
String[] newChar = new String[n];
char[] strs = str.toCharArray(); //将字符串转换成字符数组
scanner.next() 读取下一个字符串,遇到空格就不在读入
scanner.nextLine()读取下一行
scanner.nextInt() 读取数字
读取带空格的字符串,并以空格分隔
public class main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String stringArray[] = input.split("\\s");
int num[] = new int[stringArray.length];
for(int i=0; i<stringArray.length; i++){
num[i]=Integer.parseInt(stringArray[i]);
System.out.print(num[i]);
}
}
}
读取文件中的输入的数字:
Scanner ss = new Scanner(new File("src\\fangcha2.txt"));
int temp=0;
while(ss.hasNext()){
String[] str=ss.nextLine().split(" ");
}