[英]How to read a string input containing spaces using Scanner and print it out in Java?
How can I accept the string as input in Java from the user by using the Scanner
class that includes spaces and printing the accepted input with spaces? 如何通过使用包含空格的
Scanner
类并使用空格打印接受的输入,来从用户中接受字符串作为Java中的输入?
Here is my code so far: 到目前为止,这是我的代码:
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
double j=scan.nextDouble();
String k=scan.next.split(' ');
// Write your code here.
System.out.println("String: " + k);
System.out.println("Double: " + j);
System.out.println("Int: " + i);
}
}
This is a--input This is a--output 这是一个输入这是一个输出
I don't quite understand what problem you are experiencing, but I advise you to read all strings like this: 我不太了解您遇到的是什么问题,但是我建议您阅读所有这样的字符串:
String myString = scan.nextLine();
If you want to split it on every space, then just do it like this: 如果要在每个空间上拆分它,则只需执行以下操作:
String[] mySplitString = myString.split(" ");
Note that the method above accepts a string variable and not a char variable. 注意上面的方法接受一个字符串变量而不是一个char变量。 You have to store split strings into an array of strings (String[]), because the split method will generate one or multiple strings, depending on how many spaces there are in an input.
您必须将拆分的字符串存储到字符串数组(String [])中,因为split方法将生成一个或多个字符串,具体取决于输入中有多少空格。
You can use nextLine() function of Scanner Class. 您可以使用Scanner Class的nextLine()函数。 Like this:-
像这样:-
Scanner s = new Scanner(System.in);
String str = s.nextLine(); //for getting input
System.out.print(str); //for Printing
Hope this will help you. 希望这会帮助你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.