我不知道如何用我选择的数字交换数组中的最小数字。我必须使用的方法是swapNum()。然后在我这样做之后,我必须打印出数组,但是我从swapNum()做了修改
public class Data
{
private int numbers[] = {1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 10,};
private int smallNum = numbers[0];
private int largeNum = numbers[0];
private int countNum = 0;
public void setsmallNum(int smallNum)
{ this.smallNum = smallNum; }
public void setlargeNum(int largeNum)
{ this.largeNum = largeNum; }
public void setcountNum(int countNum)
{ this.countNum = countNum; }
public int getsmallNum()
{
for(int i = 0; i < numbers.length; i++)
{
if(numbers[i] < smallNum)
{
smallNum = numbers[i];
}
}
return smallNum;
}
public int getlargeNum()
{
for(int i = 0; i < numbers.length; i++)
{
if(numbers[i] > largeNum)
{
largeNum = numbers[i];
}
}
return largeNum;
}
public int getcountNum()
{
int counter = 0;
for(int i = 0; i < numbers.length; i++)
{
if(numbers[i] == countNum)
{
counter++;
System.out.println("Number is at index: " + i);
}
}
return counter;
}
public int swapNum()
{
/* swap lowest number in array with a selected number
that I choose such as d.setcountNum(5)
*/
}
public static void main(String[] args)
{
Data d = new Data();
d.getlargeNum();
d.getsmallNum();
d.setcountNum(5);
System.out.println("Largest number: " + d.getlargeNum());
System.out.println("Smallest number: " + d.getsmallNum());
System.out.println("Number appears " + d.getcountNum() + " times");
// System.out.println(Print out the modified array from swapNum() method)
}
}
答案 0 :(得分:0)
根据您的代码,最小的数字存储在全局smallNum
变量中。
使用此值创建一个函数,您可以选择多个参数作为参数。然后找到数组中的最小数字并使用temp变量进行交换。
public int swapNum(int num){
int temp = 0;
for(int i=0; i<numbers.length; i++)
if(numbers[i] == smallNum){ //find smallest value in array.
temp = numbers[i];
numbers[i] = num;
}
}
return temp; //You can return the value that was swapped
}
创建另一个显示numbers
数组内容的函数。随时调用它。
public void display(){
for(int i=0; i<numbers.length; i++){
System.out.print(numbers[i]+" ");
}
System.out.println();
}
可以进行一些修改以提高代码效率。