Issue
The program has a 2D array of size [5][3] (columns and rows respectively). I have a problem on how to print the user input, but I think the code below works fine (also not sure).
My question is: How to print the array in this order?
Shirt # 1: [S,red,bench] Shirt # 2: [L,blue,Wrangler]
...so on
Below is the code.
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int sNumber = 4;
// ang sNumber ay Shirt Number/Shirt Numbering
String sSize,sColor,sBrand;
String[][] shirt = new String[5][3];
for (int counter = 0; counter <= sNumber; counter++){
System.out.println("Enter Shirt#" + (counter + 1) + " Size: ");
shirt[counter][0] = input.next();
System.out.println("Enter Shirt#" + (counter + 1) + " Color: ");
shirt[counter][1] = input.next();
System.out.println("Enter Shirt#" + (counter + 1) + " Brand: ");
shirt[counter][2] = input.next();
}
}
}
Solution
Add this lines of code after your for
:
// this loop will print the array
for (int counter = 0; counter <= sNumber; counter++) {
System.out.print("Shirt # " + (counter + 1) + " : ["
+ shirt[counter][0] + ","
+ shirt[counter][1] + ","
+ shirt[counter][2] + "] ");
}
The final code will look like this:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int sNumber = 4;
// ang sNumber ay Shirt Number/Shirt Numbering
String sSize, sColor, sBrand;
String[][] shirt = new String[5][3];
for (int counter = 0; counter <= sNumber; counter++) {
System.out.println("Enter Shirt#" + (counter + 1) + " Size: ");
shirt[counter][0] = input.next();
System.out.println("Enter Shirt#" + (counter + 1) + " Color: ");
shirt[counter][1] = input.next();
System.out.println("Enter Shirt#" + (counter + 1) + " Brand: ");
shirt[counter][2] = input.next();
}
// this loop will print the array
for (int counter = 0; counter <= sNumber; counter++) {
System.out.print("Shirt # " + (counter + 1) + " : ["
+ shirt[counter][0] + ","
+ shirt[counter][1] + ","
+ shirt[counter][2] + "] ");
}
}
}
Answered By - Ribas Developer
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.