gpt4 book ai didi

java - 获取数组并将其压缩的方法

转载 作者:行者123 更新时间:2023-11-30 04:32:12 25 4
gpt4 key购买 nike

给出的作业是,编写一个程序,从文件中读取数字,从这些数字构造一个数组,并将所有零移到数组的末尾。

例如。

之前:0, 9, 7, 0, 0, 23, 4, 0

之后:9, 7, 23, 4, 0, 0, 0, 0

经过大约两个小时的研究,我想出了这个。

import java.io.*;
import java.util.Scanner;

public class Compactor{

Scanner in;
private int numNum = 0;

public void calcNumNum(){
try{
in = new Scanner(new File("compact.txt"));
while(in.hasNext()){
int dumpVal = in.nextInt();
numNum++;
}
makeArray(numNum);
}catch(IOException i){
System.out.println("Error: " + i.getMessage());
}
}

private void makeArray(int x){
int i = 0;
int[] arrayName = new int[x];
try{
in = new Scanner(new File("compact.txt"));
while(i < x){
arrayName[i] = in.nextInt();
i++;
}
compact(arrayName);
}catch(IOException e){
System.out.println("Error: " + e.getMessage());
}
}

private void compact(int[] x){
int counter = 0;
int bCounter = (x.length - 1);
for(int j = 0; j < x.length; j++){
if(x[j]!=0){
x[counter] = x[j];
counter++;
}else{
x[bCounter] = x[j];
bCounter--;
}
}
printArray(x);
}

private void printArray(int[] m){
int count = 0;
while(count < m.length){
System.out.print(m[count] + " ");
count++;
}
}

}

提供给我们的文件是:0, 6, 13, 0, 0, 75, 33, 0, 0, 0, 4, 2,9 21, 0, 86, 0, 32, 66, 0 , 0。

我得到的是:6, 13, 75, 33, 4, 29, 21, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0。(没有当然,我只是把逗号放在里面以便于阅读。)

任何人都可以给我关于如何解决这个问题的见解,或者也许我应该用不同的方法重新开始我的代码,整个,

if(x[j]!=0){
x[counter] = x[j];
counter++;
}else{
x[bCounter] = x[j];
bCounter--;
}

我只是即时完成,认为它会工作得很好,显然它在超过最后一个值后继续运行,并不断设置越来越多的值向后计数为零,但不知道如何让它工作,任何帮助将不胜感激。

最佳答案

使用 compact() 就快完成了:

private void compact(int[] x) {
int counter = 0;
for (int j = 0; j < x.length; j++) {
if (x[j] != 0) {
x[counter++] = x[j];
}
}
while (counter < x.length) {
x[counter++] = 0;
}
printArray(x);
}

关于java - 获取数组并将其压缩的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14375219/

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