При новой итерации данные переписываются, как воспользоваться массивом?
Код может хранить данные в теле while только одну итерацию, при повторной итерации данные переписываются.
Каким можно воспользоваться синтаксисом, чтобы данные записывались и при повторной итерации не переписывались, а добавлялись, причем не сложением, а отдельным значением?
import java.util.Arrays;
import java.util.Scanner;
public class Main {
static void printList(String[] x, int[] m) {
for (int i = 1; i < x.length; i++) {
System.out.println(i + "." + x[i] + "," + " цена: " + m[i] + " руб.");
}
System.out.println("\n" + "Выберите номер товара и колличество для завершения покупки введите - 'end'");
}
public static void main(String[] args) {
System.out.println("В нашем магазине Вы можете приобрести следующие товары: ");
printList(Food.product, Food.prices);
int productNumber = 0;
int currentPrices = 0;
int porductCount = 0;
int sum = 0;
Scanner scanner = new Scanner(System.in);
while (true) {
String input = scanner.nextLine();
if (input.equals("end")) break;
String[] part = input.split(" ");
productNumber = Integer.parseInt(part[0]); // здесь не понял, как заполнить массив с каждой новой итерацией
porductCount = Integer.parseInt(part[1]); // после каждой итерации данные в массиве переписываются
currentPrices = Food.prices[productNumber];
sum = productNumber + porductCount * currentPrices;
}
System.out.println("Наименование товара Количество Цена/за.ед Общая стоимость" + "\n"
+ Food.product[productNumber] + " " + porductCount + " " + currentPrices
+ " " + sum);
}
}
Ответы (2 шт):
Если правильно понял задачу, то Вам следует добавить какой-то вид списка или расширяемого массива. Обычно используют ArrayList. Код будет выглядеть примерно так:
List<int[]> cart = new ArrayList<>();//декларируем список массивов
System.out.println("В нашем магазине Вы можете приобрести следующие товары: ");
int productNumber;
int currentPrices;
int porductCount;
int sum;
Scanner scanner = new Scanner(System.in);
while (true) {
String input = scanner.nextLine();
if (input.equals("end")) break;
String[] part = input.split(" ");
productNumber = Integer.parseInt(part[0]);
porductCount = Integer.parseInt(part[1]);
currentPrices = Food.prices[productNumber];
sum = productNumber + porductCount * currentPrices;
//добавляем товар в список массивов
cart.add(new int[]{productNumber, porductCount, currentPrices, sum});
}
System.out.println("Наименование товара Количество Цена/за.ед Общая стоимость");
for (int[] ints : cart) {
System.out.printf("%d\t%d\t%d\t%d\n",Food.product[ints[0]], ints[1], ints[2], ints[3]);
}
Т.е выбранные товары начинают добавляться в список выбранных товаров, а потом он выводится построчно.
З.Ы. Сами нормально отформатируйте вывод как надо.
З.З.Ы. Советовал бы вам почитать что-то про коллекции java.
Ваш код должен выглядеть примерно так:
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
private final static List<Food> foods = Stream.of(
new Food("Товар 1", 5),
new Food("Товар 2", 2),
new Food("Товар 3", 7)
).collect(Collectors.toList());
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.println("В нашем магазине Вы можете приобрести следующие товары: ");
printList(foods);
System.out.println("Выберите номер товара и колличество для завершения покупки введите - 'end'");
List<Order> orders = new ArrayList<>();
while (true) {
String input = scanner.nextLine();
if (input.equals("end")) break;
parseOrder(input).ifPresent(order -> orders.add(order));
}
printList(orders);
int totalCost = orders.stream().mapToInt(Order::getTotalPrice).sum();
System.out.println("Общпая стоимость покупок: " + totalCost);
}
}
private static Optional<Order> parseOrder(String input) {
try {
String[] part = input.split(" ");
return Optional.of(new Order(foods.get(Integer.parseInt(part[0].trim()) - 1),
Integer.parseInt(part[1].trim())));
} catch (Exception e) {
return Optional.empty();
}
}
private static void printList(List list) {
for (int i = 0; i < list.size(); i++) {
System.out.println((i+1) + "." + list.get(i));
}
}
}
class Order{
private final Food food;
private final int number;
private final int totalPrice;
public Order(Food food, int number) {
this.food = food;
this.number = number;
this.totalPrice = food.getPrice()*number;
}
public Food getFood() {
return food;
}
public int getNumber() {
return number;
}
public int getTotalPrice() {
return totalPrice;
}
@Override
public String toString() {
return food + ", количество: " + number + ", общая стоимость: " + totalPrice;
}
}
class Food{
private final String product;
private final int price;
public Food(String product, int price) {
this.product = product;
this.price = price;
}
public String getProduct() {
return product;
}
public int getPrice() {
return price;
}
@Override
public String toString() {
return product + ", цена: " + price + " руб.";
}
}
Попробуйте разобраться, не стесняйтесь задавать вопросы