如何从java中的控制台获取带空格的字符串作为输入? [英] How to get a string with blank spaces as input from console in java ?
本文介绍了如何从java中的控制台获取带空格的字符串作为输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
import java.util.Scanner;
public class 解决方案{
public static void main( String [] args){
扫描仪扫描= 新扫描仪(系统。在跨度>);
int i = scan.nextInt();
double d = scan.nextDouble();
String s;
s = scan.nextLine();
系统。 out .println( String : + s);
系统。 out .println( Double : + d);
系统。 out .println( Int : + i);
}
}
这是代码。
我应该做些什么改变为了接受一个带有空格作为输入的字符串并打印出来的代码?
我尝试了什么:
输入(stdin):
42
3.1415
早上好,祝你有愉快的一天!
我的输出(标准输出):
字符串:
双倍:3.1415
Int:42
预期输出:
字符串:早上好,祝你有愉快的一天!
双倍:3.1415
Int:42
解决方案
试试这个 -
// s = scan.nextLine();
扫描仪扫描仪= 新扫描仪;
希望,它有助于:)
确定。这将是问答类型。我刚才找到了问题的答案。
我在 nextInt / nextDouble之后放置了 nextLine 方法大>方法。
我忘了 nextInt 方法不会读取/ n换行符这个事实用户通过stdin给出。
所以在放置 nextLine 方法之前,空白 scan.nextLinemethod 会读取通过/ n换行符。
更正后的代码如下所示:
scan.nextLine();
String s;
s = scan.nextLine();
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
double d = scan.nextDouble();
String s;
s = scan.nextLine();
System.out.println("String: " + s);
System.out.println("Double: " + d);
System.out.println("Int: " + i);
}
}
This is the code.
What changes should i make to the code inorder to accept a string with blank spaces as input and print it ?
What I have tried:
Input (stdin):
42
3.1415
Good Morning have a nice day!
My Output (stdout):
String:
Double: 3.1415
Int: 42
Expected Output:
String:Good Morning have a nice day!
Double: 3.1415
Int: 42
解决方案
Try this-
//s = scan.nextLine(); Scanner scanner = new Scanner(s);
Hope, it helps :)
Ok. This is going to be a Question and Answer type. I found the answer for my question just now.
I have placed the nextLine method just after the nextInt/nextDouble method.
I forgot the fact that nextInt method wouldn't read the "/n" newline character that is given through stdin by user.
So before placing the nextLine method, a blank scan.nextLinemethod would read through the "/n" newline character.
Corrected code looks like this:
scan.nextLine(); String s; s = scan.nextLine();
这篇关于如何从java中的控制台获取带空格的字符串作为输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文