繁体   English   中英

使用 Java Scanner 打印整行字符串

[英]Print entire line string with Java Scanner

如何获得以下内容以打印字符串输入? 首先我插入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

这是因为 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

这是帮助您打印整行字符串的示例代码。

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

暂无
暂无

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

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