使用Scanner类在一行内读取以空格分隔的字符串的方法是什么?

huangapple go评论83阅读模式
英文:

How to read space separated string in one line using Scanner class?

问题

     Scanner sc = new Scanner(System.in);
     int t = sc.nextInt();
     String s = sc.nextLine();
     String[] arr = s.split(" ");
     //无法通过空格" "拆分字符串。
英文:
 Scanner sc = new Scanner(System.in);
 int t = sc.nextInt();
 String s = sc.nextLine();
 String[] arr = s.split(" ");  
 //not able to split the string by whitespace" ".

答案1

得分: 1

nextLine在这里首先读取了行的剩余部分根据文档,因此您需要再调用nextLine

Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
sc.nextLine(); // 添加了这一行
String s = sc.nextLine();
String[] arr = s.split(" ");
英文:

nextLine here reads the rest of the line first according to the docs, so you need another call to nextLine.

Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
sc.nextLine(); // added
String s = sc.nextLine();
String[] arr = s.split(" ");

huangapple
  • 本文由 发表于 2020年4月9日 19:37:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/61120275.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定