使用Java Scanner打印整个行字符串

时间:2018-02-09 09:00:25

标签: java

如何获取以下内容以打印字符串输入?首先,我插入int,然后插入double,然后插入字符串,但代码不返回整个字符串。

import java.util.Scanner;

public class TestScanner {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        int i = scan.nextInt();
        double d = scan.nextDouble();
        String s = scan.next();

        System.out.println("String: " + s);
        System.out.println("Double: " + d);
        System.out.println("Int: " + i);
    }
}

这是测试结果。从下面可以看到它打印int和double但不打印字符串。

3
2.5
Hello World

String: Hello
Double: 2.5
Int: 3

2 个答案:

答案 0 :(得分:0)

这是因为scan.nextDouble()方法不使用输入的最后一个换行符,因此在下一次调用scan.nextLine()时会消耗该换行符。

为此,在scan.nextDouble()之后调用一个空白的scan.nextLine()来使用该行的其余部分,包括换行符。

这是一个示例代码,可以帮助您了解可能的解决方法:

public class newLineIssue {
    public static void main(String args[]) throws InterruptedException {
        Scanner scan = new Scanner(System.in);

        int i = scan.nextInt();
        double d = scan.nextDouble();
        scan.nextLine();
        String s = scan.nextLine();

        System.out.println("String: " + s);
        System.out.println("Double: " + d);
        System.out.println("Int: " + i);
        }
    }

我的输出为:

1
22.5
dsfgdsg
String: dsfgdsg
Double: 22.5
Int: 1

答案 1 :(得分:0)

这是示例代码,可帮助您打印String的整个行。

package com.practice;

import java.util.Scanner;

public class Practice {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
       
        int i = scan.nextInt();       // Read the Integer data type

         double d = scan.nextDouble();      // Read the Double data type
         
         scan.nextLine();          // Read the entire line of String
         String s = scan.nextLine();
                 
        System.out.println("String: " + s);
        System.out.println("Double: " + d);
        System.out.println("Int: " + i);
    }
}

输入

45
56.24
Hi i am java developer!

输出

String: Hi i am java developer!
Double: 56.24
Int: 45
相关问题