이 코드와 관련하여 질문이 있습니다. 일부 메소드에서는 리턴과 주석이 있음을 알 수 있습니다. 그 이유는 void 메소드 대신 return 메소드를 사용해야하기 때문입니다. 선생님은 저를 무효 클래스로 변환하라고 말씀 하셨지만, 반환 할 필드 변수를 수정하는 방법이 아닙니까? 때로는 선생님이 프로그래밍에 대해 많이 알지 못하는 것 같거나 의심이 있기 때문에 의심의 여지가 있습니다. 사전에 도움을 주셔서 감사드립니다.자바의 메소드 선언
공용 클래스 ArraysClass {
private int[] array;
private int arrayLength;
public ArraysClass() {
setArrayLength();
array = new int[arrayLength];
}
public int setArrayLength() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number to set the length of the array:");
arrayLength = scanner.nextInt();
System.out.println();
return arrayLength;
}
public void fillArray() {
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < arrayLength; i++) {
System.out.println("Type a number to fill position " + i);
array[i] = scanner.nextInt();
}
// return array;
System.out.println();
}
public void findNumber() {
Scanner scanner = new Scanner(System.in);
int tofind, position;
System.out.println("Enter a number to search it in the array:");
tofind = scanner.nextInt();
position = Arrays.binarySearch(array, tofind);
if (position < 0) {
System.out.println("We did not find your number.");
} else {
System.out.println("The number you typed is in the next position: " + position);
}
System.out.println();
}
public void fillMethod() {
Scanner scanner = new Scanner(System.in);
int tofill;
System.out.println("Enter a number to fill the entire array with:");
tofill = scanner.nextInt();
Arrays.fill(array, tofill);
System.out.println();
//return array;
}
public void Sortmethod() {
Arrays.sort(array);
//return array;
}
private void showArray() {
System.out.println("Showing the array...");
for (int i = 0; i < arrayLength; i++) {
System.out.println(array[i]);
}
System.out.println();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArraysClass arrayobj = new ArraysClass();
int choose;
do {
do {
System.out.println("1-Fill the array");
System.out.println("2-Find a number in the array");
System.out.println("3-Fill the entire array with a number");
System.out.println("4-Sort the array");
System.out.println("5-Show the array");
System.out.println("6-Exit");
System.out.println("Which one do you want to use?:");
choose = scanner.nextInt();
} while (choose < 1 && choose > 6);
switch (choose) {
case 1:
arrayobj.fillArray();
break;
case 2:
arrayobj.findNumber();
break;
case 3:
arrayobj.fillMethod();
break;
case 4:
arrayobj.Sortmethod();
break;
case 5:
arrayobj.showArray();
break;
case 6:
break;
}
} while (choose != 6);
}
} 일반적으로
죄송 합니다만, 입/출력 작업과 메서드를 혼합하면 무엇을 의미합니까? 나는 그것을 정말로 이해하지 못합니다 – Seveeen
예를 들어 fillArray에서 : Scanner scanner = new Scanner (System.in); System.in에서 항상 가치를 읽을 수 있다는 것을 어떻게 미리 알 수 있습니까? array.length라고 부르려고합니다. 당신은 그렇게 할 수 없습니다. 코드에서는 항상 콘솔에서 값을 읽고 콘솔에 값을 쓰는 것으로 가정합니다. –