2015-06-20 47 views
0

我想創建一個購物清單程序,在輸入產品的名稱和價格後,將它們輸入到數組中,然後打印出這個代碼有哪些錯誤的整個列表?從掃描儀到陣列的寫入數據

import java.util.Scanner; 
import java.util.Arrays; 

public class List { 
    public static void main (String[] args){ 
     Scanner sc = new Scanner(System.in); 
     String [] name = new String[4]; 
     double [] price = new double[4]; 

     for (int i =0; i<name.length; i++) { 
      System.out.println("name"); 
      name[i] = sc.nextLine(); 

      System.out.println("price"); 
      price[i] = sc.nextDouble(); 
     } 
     System.out.println("your product: " + Arrays.toString(name) + Arrays.toString(price)); 
    } 
} 
+2

這是當你對混合'nextLine()'和'nextDouble()' – Rishav

+0

而不是'sc.nextDouble電話會發生什麼()','sc.nextLine()'並解析爲'Double'。 – Rishav

回答

1

Scanner#nextLine()讀取整行。

Scanner#nextDouble()讀取下一個標記而不是整行。

因此,對於循環nextLine()的第二次迭代,將讀取您放置令牌的相同行,使您在name[1]中爲空,併爲double[1]=sc.nextDouble()錯誤。

Docs

的問題可以通過添加nextLine()後要解決讀雙可變

for (int i =0; i<name.length; i++) { 
      System.out.println("name"); 
      name[i] = sc.nextLine(); 

      System.out.println("price"); 
      price[i] = sc.nextDouble(); 

      if(i<name.length-1) 
      sc.nextLine();  //will skip the line 
} 

Demo

+0

在發佈之前花點時間閱讀你的答案。 – Rishav

+0

我說錯了什麼@RishavKundu – silentprogrammer

+0

你的答案有很多格式問題。現在可以。 – Rishav

0

所以我是用input.nextDouble(),它是給我鍵入不匹配錯誤

public static void main (String[] args) 
{ 
    Scanner input = new Scanner(System.in); 
    double[] numbers = new double[4]; 
    String [] name = new String[4]; 

    for (int i = 0; i < numbers.length; i++) 
    { 
     System.out.println("Please enter product price"); 
     numbers[i] = Double.parseDouble(input.nextLine()); 

     System.out.println("Please enter product name"); 
     name[i] = input.nextLine(); 
    } 

System.out.println(Arrays.toString(name)); 
System.out.println(Arrays.toString(numbers)); 
} 
+0

解釋你已經改變了什麼以及你爲什麼這麼做是個好主意:)。 – Tom

2

您可以使用nextLine()而不是nextDouble()來解決此問題。但是,你需要將其解析爲雙作爲你的價值聲明爲雙:

Scanner sc = new Scanner(System.in); 
String [] name = new String[4]; 
double [] price = new double[4]; 

for (int i =0; i<name.length; i++) { 
    System.out.println("name"); 
    name[i] = sc.nextLine(); 
    System.out.println("price"); 
    price[i] = Double.parseDouble(sc.nextLine()) ; 
} 
System.out.println("your product: " + Arrays.toString(name) + Arrays.toString(price)); 
+0

這個版本更好(沒有我在其他答案中提到的錯誤[這裏](http://stackoverflow.com/questions/30955555/loop-array-output),它值得它upvote),但有一個問題:爲什麼你選擇了不同的「風格」來解決這個問題?只是一個好奇心,因爲這兩個版本都可以工作。 – Tom