LAB Activity 03252026
2026-03-25 13:47
Tags: #java
Author: Duke Hsu
Topic
- Array
- Array of object
- for loop
- Scanner
Note
After sc.nextInt(); and sc.nextDouble(); you need add sc.nextLine();
```
Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66 | package arrayslabactvity;
import java.util.Scanner;
/**
*
* @author dukehsu
*/
public class ArraysLabActvity {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//define array of object size .
System.out.print("Plz enter number of Products: ");
int numProducts = sc.nextInt();
sc.nextLine();
//create a array of object
Product[] products = new Product[numProducts];
//for loop to ask user input product name and price
for(int i=0; i<products.length; i++){
Product p = new Product(); //create a object
System.out.print("Plz Enter Product " +(i+1)+" Name: ");
p.prodName=sc.nextLine();
System.out.print("Plz Enter Product " +(i+1)+" Price: ");
p.price = sc.nextDouble();
sc.nextLine();
products[i]=p;
}//end of for loop
System.out.println("--------");
//use forloop to access the arrays
for(int i = 0; i < numProducts; i++){
products[i].display();
}//end of for loop
}//end of main methods
}
//Product Class
class Product{
//attribute
String prodName;
double price;
// display method
void display(){
System.out.println("Product Name is : " + prodName);
System.out.println("Produc Price is: "+ price);
}
}//end of Product class
|
References