Метод массива с оператором If в JavaJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Метод массива с оператором If в Java

Сообщение Anonymous »

Я аспирант, изучаю программу Java. В качестве домашнего задания нам нужно сделать следующее:
  • Создать меню пунктов, в котором пользователь сможет вводить варианты выбора в массив


    li>
    Создайте метод, который определяет цены выбранных товаров и возвращает сумму
Прямо сейчас , мои выходные данные показывают, что общая сумма, возвращаемая методом, на самом деле представляет собой сложение всех цен в операторе if, а не координируя их с массивом пользовательского ввода, который был скопирован (см. пример вывода внизу). Мы не затронули ничего, кроме стандартного массива (никаких ArrayList и других методов). Пожалуйста, дайте совет, я сделаю все возможное, чтобы разобраться.

Код: Выделить всё

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

public class Online_Purchasing_HW6 {

public static final int ARRAY_LENGTH = 10;      //Length of the array

public static void main(String[] args) {
Scanner input = new Scanner(System.in); //Reads user input
int[] naMenuChoice = new int [ARRAY_LENGTH];   //Array for items chosen
String[] naMenu = new String [ARRAY_LENGTH];   //Array for menu items
int[] naItemPrice = new int [9];  //Array for item prices
String sCustomerName;         //String for customer's name
int nChoice = 0;             //Option chosen in menu by user/Used as Index
int nSum = 0;                //Sum of items chosen
double dTotalPrice = 0;      //Total price plus taxes
double dTaxes = 0;           //Total taxes to be applied to total

//Declare Constants
final int SENTINEL = 10;               //Used to end loop
final double SALES_TAX = 0.065;         //Sales tax to be used

//Choices for menu denoted by strings
String sChoice1 = "1. Smartphone" + "\t" + "\t" + "$249";
String sChoice2 = "2. Smartphone Case" + "\t" + "$39";
String sChoice3 = "3. PC Laptop" + "\t" + "\t" + "$1149";
String sChoice4 = "4. Tablet" + "\t" + "\t" + "$349";
String sChoice5 = "5. Tablet Case" + "\t" + "\t" +  "$49";
String sChoice6 = "6. eReader" + "\t" + "\t" + "$119";
String sChoice7 = "7. PC Desktop" + "\t" + "\t" + "$899";
String sChoice8 = "8. LCD Monitor" + "\t" + "\t" + "$299";
String sChoice9 = "9. Laser Printer" + "\t" + "$399";
String sChoice10 = "10.  Complete my order";

//Prompt user for name
System.out.print("Please enter your name: ");

//Read customer's name
sCustomerName = input.nextLine();

//Menu of items for purchase
System.out.print("\n");
System.out.println("Best Purchase Products");
System.out.println(sChoice1);
System.out.println(sChoice2);
System.out.println(sChoice3);
System.out.println(sChoice4);
System.out.println(sChoice5);
System.out.println(sChoice6);
System.out.println(sChoice7);
System.out.println(sChoice8);
System.out.println(sChoice9);
System.out.println(sChoice10);

//Prompt user for item selection
System.out.print("Please select an item from the menu above: ");

naMenuChoice[nChoice] = input.nextInt();

//Loop to read integers from user
while (naMenuChoice[nChoice] != SENTINEL) {

//adds 1 everytime more than one item is chosen by the user
nChoice++;

//Prompt user for another choice since he/she has not chosen option "10"
System.out.print("Please select another item from the menu above: ");
naMenuChoice[nChoice] = input.nextInt();

} //end of while loop

System.out.print(Arrays.toString(naMenuChoice));
//If option 10 if chosen, the loop will end with this message
System.out.println("\n" + "Thank you for ordering with Best Purchase, " + sCustomerName );

//call calculateTotalPrice method passing Array
nSum = nCalculatePrice(naMenuChoice);

//Formulas

//Sales Tax
dTaxes = SALES_TAX * nSum;

//Total Amount Due
dTotalPrice = dTaxes + nSum;

System.out.println("Total items ordered: " + nChoice);
System.out.println("Price of items ordered: $" + nSum);
System.out.println("Sales tax: $" + dTaxes);
System.out.println("Total amount due: $" + dTotalPrice);
}//end of main method

//Method for calculating price
public static int nCalculatePrice(int[] naChoicesToPrice){
int nTotalPrice = 0; //int value to return
int nIndex = 0; //used as counter
int nItemPrice = 0; //used to assign price of items
int[] naAddedPrices = new int[ARRAY_LENGTH]; //new array for assigning prices

//For loop to sum up all entries from naItemPrice array
for (nIndex = 0; nIndex < ARRAY_LENGTH; nIndex++){
naAddedPrices[nIndex] = naChoicesToPrice[nIndex];
//end of For Loop

if (nIndex == 1) {
nItemPrice = 249;
nTotalPrice += nItemPrice;}
if (nIndex == 2) {
nItemPrice = 39;
nTotalPrice += nItemPrice;}
if (nIndex == 3) {
nItemPrice = 1149;
nTotalPrice += nItemPrice;}
if (nIndex == 4) {
nItemPrice = 349;
nTotalPrice += nItemPrice;}
if (nIndex == 5) {
nItemPrice = 49;
nTotalPrice += nItemPrice;}
if (nIndex == 6) {
nItemPrice = 119;
nTotalPrice += nItemPrice;}
if (nIndex == 7) {
nItemPrice = 899;
nTotalPrice += nItemPrice;}
if (nIndex == 8) {
nItemPrice = 299;
nTotalPrice += nItemPrice;}
if (nIndex == 9) {
nItemPrice = 399;
nTotalPrice += nItemPrice;}
} //end of for loop

return nTotalPrice;
}//end of naCalculatePrice method

}//end of class
Соответствующий вывод программы:

Код: Выделить всё

Please enter your name: John Smith

Best Purchase Products
1. Smartphone       $249
2. Smartphone Case  $39
3. PC Laptop        $1149
4. Tablet       $349
5. Tablet Case      $49
6. eReader      $119
7. PC Desktop       $899
8. LCD Monitor      $299
9. Laser Printer    $399
10. Complete my order
Please select an item from the menu above: 9
Please select another item from the menu above: 10
[9, 10, 0, 0, 0, 0, 0, 0, 0, 0]
Thank you for ordering with Best Purchase, John Smith
Total items ordered: 1
Price of items ordered: $3551
Sales tax: $230.815
Total amount due: $3781.815
Как видите, я выбрал только один пункт из меню, но он суммирует все цены. Я выполняю это задание уже две недели и впадаю в отчаяние. Я прочитал большинство статей на этом сайте, касающихся этой темы, прочитал много статей только о методах и массивах соответственно и до сих пор не могу сформулировать работающую программу. Любая помощь будет оценена по достоинству.

Подробнее здесь: https://stackoverflow.com/questions/357 ... nt-in-java
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»