我最近正在学习数组,而我一直在这个问题上受困。
我基本上必须要求用户输入将要进入数组的数字,并且必须打印出偶数百分比,并且必须按照以下格式打印所有偶数。
Even values are : 89,22,-8, 0
我的代码是这个
import java.util.*;
public class Change {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many numbers in the array?");
int num = input.nextInt();
int count=0;
int count1=0;
for (int i=1; i<=num; i++) {
System.out.println("Enter an integer: ");
count++;
int integer= input.nextInt();
if(integer%2==0) {
int list[]=new int[integer];
count1++;
}
}
System.out.println("There were "+((double)count1/count)*100+" percent of even numbers.");
System.out.println("Even values are "+Arrays.toString(list)+"");
}
}
此代码最终显示一条错误消息,提示“列表”未初始化。
我知道,因为“列表”位于for循环内,所以系统无法意识到它已被初始化,但是我不知道如何让系统识别“列表”。
任何帮助或评论都将受到赞赏。 :)
答案 0 :(得分:0)
对,首先让问题分解成几个小部分,然后逐个解决。首先,我们需要使用用户输入来创建和初始化数组。我们首先需要指定数组的大小-您已完成此操作。
Scanner input = new Scanner(System.in);
System.out.println("How many numbers in the array?");
int num = input.nextInt();
int evenCount = 0;
int[] list = new int[num]; //set array size to user input
接下来,我们需要使用用户输入的数字填充数组。
for (int i=0; i < list.length; i++){
System.out.println("Enter an integer: ");
int integer= input.nextInt();
list[i] = integer; //set array value at index to user input
}
最后,我们需要遍历数组中的每个数字并确定它是否为偶数。然后将其打印出来。
System.out.print("Evens: ");
for (int integer : list) {
if (integer % 2 == 0) { //check if even
evenCount++; //increment even number count
System.out.print(" " + integer); //print the even integers
}
}
然后,将偶数个数除以数组中的总数,得到偶数个百分比。
System.out.println("Even count: " + evenCount);
System.out.println("Percent even: " + (double)evenCount / list.length);
完整代码:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many numbers in the array?");
int num = input.nextInt();
int evenCount = 0;
int[] list = new int[num];
for (int i=0; i < list.length; i++){
System.out.println("Enter an integer: ");
int integer= input.nextInt();
list[i] = integer;
}
System.out.print("Evens: ");
for (int integer : list) {
if (integer % 2 == 0) {
evenCount++;
System.out.print(integer + " "); //print the even integers
}
}
System.out.println();
System.out.println("Even count: " + evenCount);
System.out.println("Percent even: " + (double)evenCount / list.length);
}
答案 1 :(得分:-1)
package com.inlet.ifserver;
import java.util.*;
public class x {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many numbers in the array?");
int num = input.nextInt();
int count1 = 0;
Integer[] evens = new Integer[num];
for (int i = 0; i < num; i++) {
System.out.println("Enter an integer: ");
int integer = input.nextInt();
if (integer % 2 == 0)
evens[count1++] = integer;
}
evens = Arrays.copyOfRange(evens, 0, count1);
System.out.println("There were " + ((double) count1 / num) * 100 + " percent of even numbers.");
System.out.println("Even values are " + Arrays.toString(evens) + "");
}
}