[英]How do I properly use Parallel Arrays using Java Util.Scanner?
我正在處理數組任務。 我必須使用並行數組,但是,我想讓代碼生成所需的輸出時遇到了困難。 問題出在代碼末尾要求輸入的地方。 我試過做String [i] days.nextLine
, String days next.Line
,但是它不起作用。
我將提供一張圖片以闡明我要做什么。 警告:圖片模糊。 到目前為止,我做得很好,這是提出挑戰的最后三個部分。 稍后我將添加折扣部分。 謝謝。
System.out.println("Weekday Drink Original-Price Discount-Price");
System.out.println("------------------------------------------------------");
System.out.println(day + drink + price + "IDK" );
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("-------------------------------------------------");
}
}
如果我理解正確,則您正在嘗試掃描字符串,但是您的代碼無法正常工作。 那是因為當您嘗試使用nextLine()
掃描字符串時,它正在掃描上一個nextDouble()
調用中的/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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.