如何使用Java Util.Scanner正确使用并行数组?

时间:2018-10-24 02:16:00

标签: java arrays java.util.scanner jgrasp

我正在处理数组。我必须使用并行数组,但是,我想让代码生成所需的输出时遇到了困难。问题出在代码末尾要求输入的地方。我尝试做String [i] days.nextLineString days next.Line,但不起作用。

我将提供一张图片以阐明我要做什么。警告:图片模糊。到目前为止,我做得很好,这是提出挑战的最后三个部分。稍后我将添加折扣部分。谢谢。

  System.out.println("Weekday     Drink       Original-Price     Discount-Price");
  System.out.println("------------------------------------------------------");
  System.out.println(day +  drink  + price      +          "IDK"      );

enter image description here

import java.util.Scanner;

public class Cafeteria 
{
    public static void main (String [] args)
    {
        String [] days = {"Monday: ", "Tuesday: ", "Wednesday: ", "Thursday: ", "Friday: ", "Saturday: ", "Sunday: "}; 
        String [] drinks = {"Soda", "Sweet Tea", "Lemonade", "Frozen   Lemonade", "Coffee-Hot", "Coffee-Iced", "Latte"}; 
        double [] price = {1.00, 1.50, 1.75, 2.00, 2.25, 2.50, 3.75};

        for ( int i = 0; i < days.length; i++)
        {
        }

        Scanner scan = new Scanner(System.in);
        System.out.println("What is the price of a Soda? ");
        price [0] = scan.nextDouble();

        System.out.println("What is the price of a Sweet Tea? ");
        price [1] = scan.nextDouble();

        System.out.println("What is the price of a Lemonade? ");
        price [2] = scan.nextDouble();

        System.out.println("What is the price of a Frozen Lemonade? ");
        price [3] = scan.nextDouble();

        System.out.println("What is the price of a Coffee-Hot? ");
        price [4] = scan.nextDouble();

        System.out.println("What is the price of a Coffee-Iced? ");
        price [5] = scan.nextDouble();

        System.out.println("What is the price of a Latte? ");
        price [6] = scan.nextDouble();
        System.out.println();

        System.out.println("Which day of the week do you want the discounted drink price for?");

        System.out.println("Weekday    Drink   Original-Price  Discount-Price");
        System.out.println("-------------------------------------------------");
    }
}

1 个答案:

答案 0 :(得分:0)

如果我正确理解,您正在尝试扫描字符串,但是您的代码无法正常工作。那是因为当您尝试使用nextLine()扫描字符串时,它正在扫描上一个/n调用中剩余的nextDouble()(换行符)。因此,只需执行以下操作即可:

System.out.println("What is the price of a Latte? ");
price[6] = scan.nextDouble(); // nextDouble() only returns the double value and leaves the '/n' character still in the buffer

scan.nextLine(); // Flushes out the left over '/n'
System.out.println("Which day of the week do you want the discounted drink price for?");
String day = scan.nextLine();

现在,这将获取您输入的字符串,并将其分配给变量day