gpt4 book ai didi

java - 程序不打印除 1 之外的整数

转载 作者:行者123 更新时间:2023-12-01 16:46:32 26 4
gpt4 key购买 nike

所以我之前在没有方法的情况下编写了这个程序并且它有效。然而,我制定了这些方法,然后事情就停止了。唯一有效的行是打印数组和greaterThanAverage。如果有人想看的话,我将展示原始代码。该程序只为其他所有内容打印 0。

public static void printArray (int n)
{
int[] arr = new int[n];
System.out.println("Array on one line: ");
for(int i = 0; i < arr.length; i++)
{
arr[i] = (int) (Math.random() * 500) + 1;
System.out.print(arr[i] + " ");
}
}
public static void getMax(int n)
{
int[] arr = new int[n];
int max = arr[0];

for(int i = 1; i < arr.length; i++)
{
if(arr[i] > max)
{
max = arr[i];
}
}
System.out.println();
System.out.println("Maximum: " + max);
}
public static void getMin(int n)
{
int[] arr = new int[n];
int min = arr[0];

for(int i = 1; i < arr.length; i++)
{
if(arr[i] < min)
{
min = arr[i];
}
}
System.out.println("Minimum: " + min);
}
public static void getAverage(int n)
{
double x = 0;
double y;
int[] arr = new int[n];
for(int i = 0; i < arr.length; i ++)
{
x = arr[i] + x;
}
y = x / arr.length;
System.out.println("Average: " + y);
}
public static void sumValues(int n)
{
int sum = 0;
int[] arr = new int[n];
for(int num : arr)
{
sum = sum + num;
}
System.out.println("Sum: " + sum);
}
public static void greaterThanAverage (int n)
{
int[] arr = new int[n];
int count = 1;
double y;
for(int i = 0; i < arr.length; i ++)
{
{
count ++;
}
}
System.out.println("Number of integers greater than average: " + count);
}
public static void countInc (int n)
{
int[] arr = new int[n];
int count2 = 0;
for(int i = 0; i < arr.length - 1; i++)
{
if (arr[i] < arr[i + 1])
{
count2++;
}
}
System.out.println("Number of times subsequent value increases: " + count2);
}
public static void countDec (int n)
{
int[] arr = new int[n];
int count3 = 0;
for(int i = 0; i < arr.length - 1; i++)
{
if (arr[i] > arr[i + 1])
{
count3 ++;
}
}
System.out.println("Number of times subsequent value decreases: " + count3);
}
public static void printArray3PerLn (int n)
{
System.out.println("Array with 3 elements per line: ");
int[] arr = new int[n];
for(int i = 0; i < arr.length; i++)
{
System.out.print(arr[i]+ " ");
if(i % 3 == 2)
{
System.out.println();
}
}
}
public static void main(String[] args)
{
Scanner kbd = new Scanner(System.in);
int sum = 0;
int n;
do
{
System.out.print("Enter integer n, greater than 0: ");
n = kbd.nextInt();
} while(n < 1);
System.out.println();

printArray(n);

getMax(n);

getMin(n);

sumValues(n);

getAverage(n);

greaterThanAverage(n);

countInc(n);

countDec(n);

printArray3PerLn(n);
}
}

最佳答案

这是因为你没有用数字填充数组

**public static void  countDec (int n)
{
int[] arr = new int[n]; -<<**

如果你调用该方法的示例计数Dec(5);它将用 0 填充该数组,而不是像您在 printArrayMethod 中那样使用随机数

关于java - 程序不打印除 1 之外的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61762279/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com