您好,我想请教一下Java的一个问题:题目是随机生成一个一维数组,其中有10个范围为1-100的整数,然后把这10个数打印出来。接着要用循环+判断来删掉这个数组中所有的奇数并输出剩余的数。
举个例子就是
随机生成的10个数:15 59 91 11 82 47 37 87 94 17
得到的结果要是:82 94 (就是只有偶数留着)
感谢您的解答,谢谢!
引用 皆我百晓生 小程序回复内容作答:
在Java中,可以使用continue语句来跳过当前循环中的剩余代码,并继续下一次循环的执行。在这个问题中,我们可以使用continue语句来跳过所有奇数的打印输出,只打印出偶数。
下面是一个可能的解决方案:
import java.util.Random;
public class Main {
public static void main(String[] args) {
int[] numbers = new int[10];
Random random = new Random();
// 随机生成10个1-100的整数
for (int i = 0; i < numbers.length; i++) {
numbers[i] = random.nextInt(100) + 1;
}
// 打印生成的10个数
System.out.print("随机生成的10个数:");
for (int number : numbers) {
System.out.print(number + " ");
}
System.out.println();
// 删除数组中的奇数并输出剩余的数
System.out.print("得到的结果为:");
for (int number : numbers) {
if (number % 2 == 1) {
continue; // 如果是奇数,则跳过当前循环,继续下一次循环
}
System.out.print(number + " ");
}
}
}
这段代码中,我们使用一个for循环来遍历整个数组。在每次循环中,使用if语句判断当前数是否为奇数。如果是奇数,则使用continue语句跳过当前循环,继续下一次循环。如果是偶数,则打印输出该数。
希望能解答您的问题!
如果解决你的问题,请点赞采纳,谢谢。
import java.util.Random;
public class Main {
public static void main(String[] args) {
// 创建一个长度为10的数组
int[] array = new int[10];
// 创建一个随机数生成器
Random random = new Random();
// 使用随机数生成器为数组赋值
for (int i = 0; i < array.length; i++) {
array[i] = random.nextInt(100) + 1; // 生成1-100的随机整数
}
// 循环判断数组的值,输出偶数
for (int i = 0; i < array.length; i++) {
if (array[i] % 2 == 0) {
System.out.println(array[i]);
}
}
}
}
【相关推荐】
对数组来说,实际上只能存储Java对象的内存地址。数组中存储的每个元素时是“引用”
测试类
/*一维数组的深入,数组中存储的类型为:引用数据类型*/
public class ArrayTest02 {
public static void main(String[] args) {
//创建Animal类型的数组
Animal cat = new cat();
Animal bird = new bird();
Animal[] animals = {cat,bird};
//对Animal数组进行遍历
for (int i = 0; i < animals.length ; i++) {
Animal a = animals[i];
a.move();
}
Animal[] animals1 = {new cat(), new bird()};
//当需要调用子类特有的方法时,需要进行一个判断再向下转型,
//进而调用子类特有的方法
for (int i = 0; i < animals1.length; i++) {
if (animals1[i] instanceof cat) {
cat c = (cat) animals1[i];
c.catchmouse();
} else if (animals1[i] instanceof bird) {
bird b = (bird)animals1[i];
b.sing();
}
}
}
}
父类Animal和子类cat、bird
class Animal{
public void move() {
System.out.println("Animal move..");
}
}
class cat extends Animal{
@Override
public void move() {
System.out.println("猫在走猫步!!!");
}
public void catchmouse() {
System.out.println("猫在抓老鼠!!!");
}
}
class bird extends Animal{
@Override
public void move() {
System.out.println("老鹰在翱翔!!!");
}
public void sing() {
System.out.println("老鹰在嗷嗷叫!!!");
}
}