【问题标题】:double array won't print双数组不会打印
【发布时间】:2014-11-12 18:00:09
【问题描述】:

我在这个程序上做了更多的工作,但现在我被卡住了,因为字符串数组打印了,但我一辈子都无法打印双精度数组。任何帮助将不胜感激!

import java.util.ArrayList; 
import java.util.Arrays;
import java.lang.Double; 
import java.util.Scanner;

public class inventoryTracker
   {
      private static Scanner sc;
    private static double itemCost;

    public static void main(String[] args)
      {
     System.out.println("Welcome to the Inventory tracker"
            + "\nThis program will accept the names and costs for 10 stocked items."
            + "\nThe program will then output a table with the names, costs and,"
            + "\nprices of the items."
            + "\nPrices are calculated with a 30 percent markup on cost.");

    sc = new Scanner(System.in);

   String[] product = new String[10];
   Double[] itemCost = new Double[10];


   for (int i = 0; i < itemCost.length; i++ ){
         System.out.print("Enter the item cost :");
         itemCost [i]= sc.nextDouble();

   }

    for (int i = 0; i < product.length; i++){
            System.out.print("Enter the product name :");
            product[i] = sc.next();
    }  

    System.out.println(Arrays.toString(product));





        }


    }

【问题讨论】:

  • 能否请您发布作业的确切措辞?你可能会误解它。
  • 从字面上看,没有“并行数组”这样的东西。正如@RealSkeptic 所说,将作业的全文展示出来。

标签: java parallel-arrays


【解决方案1】:

那是因为你在你的两个 for 循环中将一个字符串分配给一个字符串数组。

product= sc.toString();

应该是

product[i] = sc.toString();

itemCost 也是如此。

【讨论】:

    【解决方案2】:

    那是因为您在两个 for 循环中将一个字符串分配给一个字符串数组。你也在做不正确的 sc.toString()。

    product= sc.toString();
    

    itemCost= sc.nextDouble();
    

    应该改为

    product[i]  = sc.nextLine();
    

    itemCost[i] = sc.nextDouble();
    

    itemCost 也是如此。

    【讨论】:

      【解决方案3】:

      您需要使用索引来设置一个值,例如:

      product[index] = value;
      

      您还使用 sc.toString() 从用户那里获取字符串。它不起作用,您需要使用 next() 方法从用户那里获取字符串。

      循环应该是这样的:

       for (int i = 0; i < product.length; i++){
          System.out.print("Enter the product name :");
          product[i] = sc.next();
       }
       for (int i = 0; i < itemCost.length; i++ ){
           System.out.print("Enter the item cost :");
           itemCost [i]= sc.nextDouble();
       }
      

      【讨论】:

      • 谢谢!这确实有点帮助,现在它接受产品名称但不接受成本。错误是 java.util.Scanner.next(Unknown Source) at java.util.Scanner.next(Unknown Source) at java.util.Scanner.throwFor(Unknown Source) 线程 "main" java.util.InputMismatchException 中的异常 (Unknown Source)在inventoryTracker.main(inventoryTracker.java:29)
      • 第 29 行是 itemCost [i]= sc.nextDouble();
      • 我没有看到不匹配,所有内容都被声明为双精度
      猜你喜欢
      • 1970-01-01
      • 2019-02-09
      • 1970-01-01
      • 2021-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-22
      • 1970-01-01
      相关资源
      最近更新 更多