英文:
Scope of the array:
问题
以下是翻译好的内容:
这里我试图找出输入数组中的最大和最小数字,所以我使用了一个尚未声明的 min 和 max 方法。但我不太确定如何在这些方法中访问我的数组,因为数组 userArray 和 array 不在方法的范围内,无法访问。有人能帮帮我吗?
package edu.skidmore.cs106.lab07.problem1;
import java.util.Scanner;
public class numberArray {
// 用于获取用户输入的方法
public int[] getUserData() {
System.out.println("您将输入多少个数字?");
Scanner keyboard = new Scanner(System.in);
// 创建变量以存储用户期望输入的值的数量
int totalNumbers = keyboard.nextInt();
// 声明并初始化一个数组
int[] userArray = new int[totalNumbers];
// 创建循环以向用户询问值
// 在循环内,将用户输入存储在数组中
for (int x = 0; x < totalNumbers; ++x) {
System.out.println("输入第 " + x + " 个数字");
int userInput = keyboard.nextInt();
userArray[x] = userInput;
}
return userArray;
}
public int minNumber() {
for (int y : array)
}
public static void main(String[] args) {
numberArray instance = new numberArray();
int array[] = instance.getUserData();
for (int element : array) {
System.out.println(element);
}
}
}
英文:
Here I am trying to find the max and min number entered into the array so I'm using a min and a max method(not declared yet) but I'm not quite sure how to access my array in these methods as the array userArray and array are not in the scope of the method and can't be accessed. can someone help me out?
package edu.skidmore.cs106.lab07.problem1;
import java.util.Scanner;
public class numberArray {
//Method to take user input
public int[] getUserData() {
System.out.println("How many numbers will you enter?");
Scanner keyboard = new Scanner(System.in);
// Create variable to store user's desired number of values
int totalNumbers = keyboard.nextInt();
// Declare and initialze an array
int[] userArray = new int[totalNumbers];
// Create a loop to ask for values from the user
// Within the loop, store user input in the array
for (int x = 0; x < totalNumbers; ++x) {
System.out.println("Enter number " + x);
int userInput = keyboard.nextInt();
userArray[x] = userInput;
}
return userArray;
}
public int minNumber() {
for (int y : array)
}
public static void main(String[] args) {
numberArray instance = new numberArray();
int array[] = instance.getUserData();
for (int element: array){
System.out.println(element);
}
}
}
答案1
得分: 0
public int minNumber(int[] userDataArray) {
// 在这里使用 userDataArray
}
...
public static void main(String[] args) {
numberArray instance = new numberArray();
int[] userDataArray = instance.getUserData();
int min = instance.minNumber(userDataArray); // 将 userDataArray 作为参数传递
}
英文:
public int minNumber(int[] userDataArray) {
// use userDataArray here
}
...
public static void main(String[] args) {
numberArray instance = new numberArray();
int[] userDataArray = instance.getUserData();
int min = instance.minNumber(userDataArray); // pass userDataArray as argument
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论