import java.util.Scanner;
public class ProgrammaD{
public static void main(String[] args){
Scanner keyboard= new Scanner(System.in);
String sequence = args[0];
char chars[] = new char[sequence.length()];
for(int i = 0; i < sequence.length(); i++){
chars[i] = sequence.charAt(i);
}
System.out.println("Insert a character");
char car = keyboard.next().charAt(0);
System.out.println("Insert an integer");
int n = keyboard.nextInt();
System.out.println("Original Array");
for(int z = 0; z < sequence.length(); z++){
System.out.println(chars[z]);
}
char chars2[] = MetodiD.occorrenzeContenuto(chars, n, car);
System.out.println("Edited Array");
for(int k = 0; k < sequence.length(); k++){
System.out.println(chars2[k]);
}
boolean condition = false;
char chars3[] = MetodiD.uniformaContenuto(chars, chars2);
for(int x = 0; x < sequence.length(); x++){
if(chars[x] == chars2[x]){
condition = false;
}
else{
condition = true;
}
}
if(condition){
for(int y = 0; y < sequence.length(); y++){
System.out.println(chars3[y]);
}
}
}
}
我无法执行最后一条if指令,我无法理解为什么。有人可以帮我解决这个问题吗?我希望程序打印MetodiD.uniformaContenuto()中返回的数组,但我无法从此代码中获取任何内容。
这是另一个班级:
public class MetodiD{
public static char[] occorrenzeContenuto(char par[], int a, char b){
int contatore = 0;
for(int i = 0; i < par.length; i++){
if(par[i] != b){
contatore++;
}else{
}
}
if(contatore > a){
for(int k = 0; k < par.length; k++){
if(par[k] != b){
par[k] = determinaCarattere(a, b);
}else{
}
}
}else{
}
return par;
}
public static char determinaCarattere(int n, char b){
int modificato;
if(n%2==0){
modificato = (int)b - n;
}else{
modificato = (int) b + n;
}
char modificato2 = (char)modificato;
return modificato2;
}
public static char[] uniformaContenuto(char par1[], char par2[]){
char rit[] = new char[par1.length];
for(int y = 0; y < par1.length; y++){
if(par1[y]<par2[y]){
rit[y] = par1[y];
}else{
rit[y] = par2[y];
}
}
return rit;
}
}
答案 0 :(得分:0)
chars 正在 occorrenzeContenuto 中设置,然后返回并分配给 chars2 ,因此它们将始终相等。尝试将此版本换成我已创建新阵列的版本,并在开始时将 par 参数复制到其中,然后将其用作返回值。
public static char[] occorrenzeContenuto(char par[], int a, char b){
char[] retVal = new char[par.length];
System.arraycopy(par,0,retVal,0,par.length);
int contatore = 0;
for(int i = 0; i < par.length; i++){
if(par[i] != b){
contatore++;
}else{
}
}
if(contatore > a){
for(int k = 0; k < par.length; k++){
if(par[k] != b){
retVal[k] = determinaCarattere(a, b);
}else{
}
}
}else{
}
return retVal;
}
问题的原因是数组参数维护对原始实例的引用,就像对象那样,而不像char这样的单个原语的行为,如下所述:Java pass by reference