簡體   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