2016-09-22 125 views
3

輸入格式沒有得到預期的輸出中

  • 第一行包含一個整數。
  • 第二行包含一個double,。
  • 第三行包含一個字符串,。

輸出格式

打印兩個整數的在第一行的總和,這兩個雙打的在第二行的總和(縮放到小數位),並且然後在第三行上的兩個級聯的字符串。這裏是我的代碼

package programs; 

import java.util.Scanner; 


public class Solution1 { 

    public static void main(String[] args) { 
     int i = 4; 
     double d = 4.0; 
     String s = "Programs "; 

     Scanner scan = new Scanner(System.in); 
     int i1 = scan.nextInt(); 
     double d1 = scan.nextDouble(); 
     String s1 = scan.next(); 

     int i2 = i + i1; 
     double d2 = d + d1; 
     String s2 = s + s1; 
     System.out.println(i2); 
     System.out.println(d2); 
     System.out.println(s2); 
     scan.close(); 
    } 
} 

輸入(stdin)

12 
4.0 
are the best way to learn and practice coding! 

你的輸出(stdout)

16 
8.0 
programs are 

期望輸出

16 
8.0 
programs are the best place to learn and practice coding! 

任何幫助,將不勝感激!

+1

這是偉大的,你在這裏提供一個完整的計劃 - 在未來,這將是很好,如果你可以把它降低到最小的* *例子。鑑於閱讀數字的位已經工作,你可以減少這基本上'掃描儀掃描=新掃描儀(System.in); String s1 = scan.next(); System.out.println(s1);' –

+0

[Scanner](https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#next())將其輸入分解爲令牌**使用分隔符模式,默認情況下匹配空格** .. public String next() 查找並返回來自此掃描器的下一個完整令牌。**一個完整的標記前後有與分隔符**匹配的輸入。即使先前調用hasNext()返回true,該方法也可能在等待輸入進行掃描時阻塞。 – Tibrogargan

+0

我看不出這個問題是怎麼回事,+3,沒有任何理由看到更好的問題與負面回購下去,似乎這傢伙再次做了他的魔力。 –

回答

3

Scanner.next()讀取下一個令牌。默認情況下,空格用作記號之間的分隔符,因此您只能得到輸入的第一個單詞。

聽起來好像要讀取整個,因此請使用Scanner.nextLine()。根據this question,您需要撥打nextLine()一次以消耗double之後的換行符。

// Consume the line break after the call to nextDouble() 
scan.nextLine(); 
// Now read the next line 
String s1 = scan.nextLine(); 
+0

如果我使用Scanner.nextLine(),那麼它也給我意想不到的輸出。請檢查出 –

+0

@KetanGupta:你是什麼意思的「請檢查出來」?檢查什麼?你還沒有告訴我們,你在說什麼...... –

+0

現在我得到這個12 4.0 8.0 方案,作爲我的輸出 –

3

您正在使用scan.next()讀取值每個空間分隔符。

但在這裏,你需要閱讀的完整產品線,以便使用

String s1 = scan.nextLine(); 
1

所有你需要做的是改變

String s1 = scan.next(); 

String s1 = scan.nextLine(); 
1

您需要使用scan.nextLine()這將讀取一個完整的行並以作爲分隔符讀取每個值。

package programs; 

import java.util.Scanner; 


public class Solution1 { 

    public static void main(String[] args) { 
     int i = 4; 
     double d = 4.0; 
     String s = "Programs "; 

     Scanner scan = new Scanner(System.in); 
     int i1 = scan.nextInt(); 
     double d1 = scan.nextDouble(); 
     String s1 = scan.nextLine(); 

     int i2 = i + i1; 
     double d2 = d + d1; 
     String s2 = s + s1; 
     System.out.println(i2); 
     System.out.println(d2); 
     System.out.println(s2); 
     scan.close(); 
    } 
} 
相關問題