Skriva ut en matris på ett speciallt sätt med krav. Java.

Permalänk

Skriva ut en matris på ett speciallt sätt med krav. Java.

Hej jag skulle behöva hjälp med att lista ut hur man kan skriva ut en int[][] array så att det liknar detta.

Pris: 199 Antal: 4
Pris: 299 Antal: 7
Pris: 600 Antal: 5

Koden ska vara en metod och dess syfte är att skriva ut alla ariklar ur en matris som har ett värde över 0 kr, eller antal.

Min nuvarande metod ser ut såhär.

public static void printArticles(int[][] articles) { for(int i = 0; i < articles.length; i++) { for(int j = 0; j < articles[i].length; j++) { System.out.println(articles[i][j]+" "); } } }

Medans hela koden ser ut såhär.

public static int[][] insertArticles(int[][] articles, int articleNumber, int noOfArticles) { articles = checkIfFull(articles, noOfArticles); int[] article = new int[2]; int[] array = new int[2]; int[] price = new int[1]; price[0] = (int) (Math.random() * 1000) + 100; int[] noOf = new int[1]; noOf[0] = (int) (Math.random() * 10) + 1; System.arraycopy(price, 0, array, 0, 1); System.arraycopy(noOf, 0, array, 1, 1); System.arraycopy(array, 0, article, 0, array.length); for (int i = 0; i < articles.length; i++) { for (int j = 0; j < articles[i].length; j++) { articles[i][articleNumber] = article[i]; } } return articles; } public static int input() { int output = sc.nextInt(); return output; } public static int[][] checkIfFull(int[][] articles, int noOfArticles) { if (noOfArticles == 10) { int largerSize = noOfArticles * noOfArticles; int[][] larger = new int[2][largerSize]; for (int i = 0; i < larger.length; i++) { for (int j = 0; j < larger[i].length; j++) { for (int k = 0; k < noOfArticles; k++) { larger[i][k] = articles[i][k]; } larger[i][j] = larger[i][j]; } } return larger; } else return articles; } public static void printArticles(int[][] articles) { for(int i = 0; i < articles.length; i++) { for(int j = 0; j < articles[i].length; j++) { System.out.println(articles[i][j]+" "); } } } public static Scanner sc = new Scanner(System.in); public static void main(String[] args) { // TODO Auto-generated method stub int articleNumber = 0, noOfArticles = 1, size = 10, rows = 2; int[][] articles = new int[rows][size]; while (true) { int option = input(); if (option == 1) { articles = insertArticles(articles, articleNumber, noOfArticles); articleNumber++; noOfArticles++; } if(option == 2) { printArticles(articles); } } }

Tack i förväg, det är en sista uppgiften för terminen.

Permalänk
Medlem

Vad är det som inte funkar?
Just nu skriver du bara ut varje enskilt element.

Visa signatur

AMD Ryzen 7 1700X 3.8 GHz 20MB | ASUS PRIME X370-PRO | MSI GeForce GTX 1080 Gaming X 8GB | G.Skill 16GB DDR4 3200 MHz CL14 Flare X | Corsair RM650x 650W