2016-08-17 72 views
0

我給這個輸入「歡迎來到HackerRank的Java教程!」但使用掃描儀類打印字符串

只通過掃描儀類打印「歡迎」字符串。

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 = scan.nextLine(); 
     scan.close(); 

     // Write your code here. 

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

如何解決這個問題?

+0

此代碼絕不會打印「歡迎」 –

+0

https://www.hackerrank.com/challenges/java-stdin-stdout/editorial您的問題有答案。 –

+0

歡迎來到Stack Overflow!您能否在解決問題的努力中獲得更好的標題和更詳細的內容信息? – manetsus

回答

0

問題是您的輸入字符串在輸入行中不包含整數和雙精度值。

如果提供12 2.56 Welcome to HackerRank's Java tutorials!,它將工作:

Scanner scan = new Scanner(System.in); 
int i = scan.nextInt(); 
double d = scan.nextDouble(); 
String s = scan.nextLine(); 
scan.close(); 

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

Java demo

輸出:

String: Welcome to HackerRank's Java tutorials! 
Double: 2.56 
Int: 12 

如果你想確保你的字符串被解析,檢查下代幣使用hasNext方法(hasNextInt()hasNextDouble()):

Scanner scan = new Scanner(System.in); 
int i = 0; 
if (scan.hasNextInt()) 
    i = scan.nextInt(); 
double d = 0d; 
if (scan.hasNextDouble()) 
    d = scan.nextDouble(); 
String s = scan.nextLine(); 
scan.close(); 

看到這個demo

+0

以上dosen't給出正確的答案我不知道如何可以接受 – Arun

+0

@Arun它對OP很好。請參閱[演示](https://ideone.com/3cNTzz)打印字符串,double和int值。您的要求與此OP不同。如果您的代碼仍然有問題,請發佈您自己的問題。 –

+1

我希望上面的解決方案不起作用,scan.nextLine();應在scan.nextDouble()後添加;那麼它就起作用了。 – Arun

1

當在讀取輸入標記和讀取完整行輸入之間切換時,需要再次調用nextLine(),因爲掃描器對象將讀取其先前讀取停止的行的其餘部分。

如果線上沒有任何東西,它只是消耗換行符並移動到下一行的開頭。

雙聲明之後,你必須寫:scan.nextLine();

+0

你的解決方案得到了工作我也給你從其他帖子相同的評論 – Arun

0

請寫出下列code..It將工作!

Scanner scan = new Scanner(System.in); 
int i = scan.nextInt(); 
double d = scan.nextDouble(); 
scan.nextLine(); 
String s = scan.nextLine(); 
scan.close(); 

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

注:如果使用nextLine()方法緊隨nextInt()或nextDouble()[讀取輸入的令牌,閱讀完整線路輸入的]方法,回想nextInt()或nextDouble()讀取整數標記;因此,整行或雙輸入行的最後一個換行符仍然在輸入緩衝區中排隊,下一個nextLine()將讀取整數或雙行的其餘部分。因此,您需要再次調用nextLine()。

+0

您的解決方案[拋出java.util.InputMismatchException](https://ideone.com/QuiNOu)。 –

+0

它會爲我工作..! –