我正在嘗試顯示陣列內的值,但其中有這些 0。使用for回圈來計算溫度的數量和溫度的值。
這是我使用的代碼:
import java.util.*;
public class Array1dTemperature {
static Scanner in = new Scanner (System.in);
static Random rng = new Random ();
public static void main(String[] args)
{
System.out.println("This program does a temperature check.");
System.out.println("Input the desired number of temperatures...");
int size = in.nextInt();
int[] temp = new int [size];
for (int i=0; i<temp.length; i )
temp[i] = 1 rng.nextInt(100);
System.out.println("The data file goes as: " Arrays.toString(temp));
Checker(temp);
}
static void Checker (int temp[])
{
int hot[] = new int [10] ; int []pleasant = new int [10]; int []cold = new int [10];
int H = 0; int P = 0; int C = 0;
for (int i=0; i<temp.length;i ) {
if (temp[i]>=85) {
hot[i] = temp[i];
H ;
}
else if (temp[i]>=60&&temp[i]<84) {
pleasant[i] = temp[i];
P ;
}
else if (temp[i]<60) {
cold[i] = temp[i];
C ;
}
}
System.out.println("number of hot: " H ", Recorded temps are: " Arrays.toString(hot) );
System.out.println("number of cold: " C ", Recorded temps are: " Arrays.toString(cold));
System.out.println("number of pleasant: " P ", Recorded temps are: " Arrays.toString(pleasant));
}
}
我嘗試更改各個陣列本身的值,但每當我嘗試列印輸出時它就會超出范圍。我本可以使用“Arraylist”來更新陣列,但是這個特定的練習題禁止使用這樣的陣列。
這是輸出
uj5u.com熱心網友回復:
因此,陣列適用于固定長度的資料,您可以提前知道有多少資料。在您的情況下,您事先不知道有多少“真實”資料將進入您的熱/冷/愉快陣列。在現實世界中,您將使用另一種資料結構(如 ),而不是用您擁有的資料填充它們ArrayList。
如果您絕對必須使用陣列,那么您首先要遍歷輸入陣列一次以了解每個陣列有多少,初始化hot適當大小的 /etc 陣列,然后再次回圈以分配它們。你不能只分配給與輸入陣列相同的索引 - 你反而想跟蹤hot(或其他)陣列中的下一個開放空間,并且每次寫入然后遞增那個柜臺
uj5u.com熱心網友回復:
您需要在填充陣列時使用H, P,C作為hot, pleasant,陣列的單獨索引,并可能應用以去除這些陣列尾部的零。coldArrays.copyOf
此外,還有一些邊緣情況需要通過設定溫度型別來解決。
static void Checker (int temp[]) {
int[] hot = new int[temp.length];
int[] pleasant = new int[temp.length];
int[] cold = new int[temp.length];
int H = 0; int P = 0; int C = 0;
for (int i = 0; i < temp.length; i ) {
if (temp[i] >= 85) {
hot[H ] = temp[i];
}
else if (temp[i] >= 60) {
pleasant[P ] = temp[i];
}
else {
cold[C ] = temp[i];
}
}
if (H < hot.length) hot = Arrays.copyOf(hot, H);
if (P < pleasant.length) pleasant = Arrays.copyOf(pleasant, P);
if (C < cold.length) cold = Arrays.copyOf(cold, C);
System.out.println("number of hot: " H ", Recorded temps are: " Arrays.toString(hot) );
System.out.println("number of cold: " C ", Recorded temps are: " Arrays.toString(cold));
System.out.println("number of pleasant: " P ", Recorded temps are: " Arrays.toString(pleasant));
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/537219.html
標籤:爪哇数组
