JAVA怎么用数组存储英文
时间: 2023-11-17 22:06:52 浏览: 40
可以使用以下方式将英文单词存储在数组中:
1. 定义一个字符串类型的数组,例如:
String[] words = new String[10];
这里我们定义了一个长度为10的字符串数组。你也可以根据需要定义任意长度的数组。
2. 将英文单词存储在数组中,例如:
words[0] = "apple";
words[1] = "banana";
words[2] = "cherry";
// 其他单词...
这里我们将apple、banana和cherry这些单词存储在了数组的前三个位置。
3. 使用循环遍历数组,例如:
for (int i = 0; i < words.length; i++) {
System.out.println(words[i]);
}
这里我们使用for循环遍历了整个数组,并将每个单词打印出来。
以上就是用数组存储英文单词的基本方法。当然,你还可以使用其他数据类型的数组来存储单词的相关信息,例如单词的长度、首字母等等。
相关问题
JAVA怎么用数组存储实时输入英文
要存储实时输入的英文,可以使用以下步骤:
1. 创建一个 Scanner 对象,用于从控制台读取用户输入的字符串。
Scanner input = new Scanner(System.in);
2. 创建一个数组,用于存储输入的字符串。
String[] words = new String[100];
3. 使用一个循环来不断读取用户输入的字符串,并将其存储到数组中。
int index = 0;
while (input.hasNext()) {
String word = input.next();
words[index++] = word;
}
4. 最后,可以遍历数组并输出存储的所有字符串。
for (int i = 0; i < index; i++) {
System.out.println(words[i]);
}
java定义数组存储手机
可以使用以下代码定义一个包含多个手机的数组:
```java
public class Phone {
private String brand;
private String model;
private int price;
// 构造方法
public Phone(String brand, String model, int price) {
this.brand = brand;
this.model = model;
this.price = price;
}
// get/set 方法省略
public static void main(String[] args) {
// 定义一个手机数组,存储三款不同品牌的手机
Phone[] phones = new Phone[3];
phones[0] = new Phone("Apple", "iPhone X", 6999);
phones[1] = new Phone("Samsung", "Galaxy S9", 5999);
phones[2] = new Phone("Huawei", "Mate 10", 4999);
// 遍历手机数组,输出手机信息
for (Phone phone : phones) {
System.out.println("品牌:" + phone.getBrand() + ",型号:" + phone.getModel() + ",价格:" + phone.getPrice());
}
}
}
```
上述代码中,我们使用 `Phone` 类来表示手机,定义了 `brand`(品牌)、`model`(型号)和 `price`(价格)三个属性,并提供了相应的构造方法和 get/set 方法。
在 `main` 方法中,我们定义了一个长度为 3 的 `Phone` 数组 `phones`,并在数组中存储了三款不同品牌的手机。最后,我们使用 for 循环遍历手机数组,输出了每个手机的品牌、型号和价格信息。