简体   繁体   English

使用 Java Scanner 打印整行字符串

[英]Print entire line string with Java Scanner

How do I get the following to print the string input?如何获得以下内容以打印字符串输入? First I insert int and then insert a double and then insert string but the code does not return the whole string.首先我插入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);
    }
}

Here is a test result.这是一个测试结果。 As you can see from below it prints the int and double but not the string.正如您从下面看到的那样,它打印 int 和 double 但不打印字符串。

3
2.5
Hello World

String: Hello
Double: 2.5
Int: 3

It's because the scan.nextDouble() method does not consume the last newline character of your input, and thus that newline is consumed in the next call to scan.nextLine().这是因为 scan.nextDouble() 方法不会消耗输入的最后一个换行符,因此在下一次调用 scan.nextLine() 时会消耗该换行符。

For this a blank scan.nextLine() call after scan.nextDouble() to consume rest of that line including newline.为此,在 scan.nextDouble() 之后调用空白 scan.nextLine() 以消耗该行的其余部分,包括换行符。

This is a sample code which might help you understand the workaround possible :这是一个示例代码,可以帮助您了解可能的解决方法:

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);
        }
    }

I got the output as :我得到的输出为:

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

This is sample code to help you to print the entire line of 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);
    }
}

Input输入

45
56.24
Hi i am java developer!

Output输出

String: Hi i am java developer!
Double: 56.24
Int: 45

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM