我正在尝试编写一种递归算法,该算法允许用户根据用户在程序中输入的数字来选择颜色。颜色的名称存储在String []数组中。我无法弄清楚为什么输出到用户的颜色与具有与用户输入的数字匹配的索引的数组中的颜色不匹配。这是我的代码:
/*
The class allows the user to search through a list a colors to pick a new
favorite color
*/
class PickAColor
{
//Global Variables
public int maxSize;
public int numOfColors;
static public String[] colors;
//Scanner
static Scanner myScan = new Scanner(System.in);
//Constructor
public PickAColor()
{
}
public PickAColor(int maxSize)
{
this.maxSize = maxSize;
this.numOfColors = 0;
colors = new String[maxSize];
populateColors();
}
//Functions
//Function to populate colors
public void populateColors()
{
//Add colors to array
push(0, "red");
push(1, "orange");
push(2, "yellow");
push(3, "green");
push(4, "blue");
push(5, "purple");
push(6, "violet");
push(7, "teal");
push(8, "magenta");
push(9, "brown");
push(10, "black");
push(11, "white");
push(12, "periwinkle");
}
//Function to push new color
public String push(int cntr, String color)
{
colors[cntr] = color;
return colors[cntr];
}
//Function to see if stack is empty
public boolean isEmpty()
{
return numOfColors == 0;
}
//Function to see if stack is full
public boolean isFull()
{
return numOfColors == maxSize;
}
//Function to loop through array
public static String Search(int num)
{
//Variables
int cntr = 0;
String color = null;
//While loop iterates through array based on user's input
while(num > cntr)
{
color = colors[cntr];
cntr++;
num--;
Search(num);
}
return color;
}
//Function to randomly organize an array
//Function to ask user for favorite color
public static void askUser()
{
//Variables
int response;
String color;
//Message user
System.out.println("Do you like your favorite color?"
+ " \nIs it still your favorite color today?"
+ " \nHow about you spin the wheel of colors to randomly"
+ " pick a new favorite color?"
+ " \nEnter a number. ");
response = Integer.parseInt(myScan.nextLine());
System.out.println("...\nGood luck! ");
color = Search(response);
//Message
System.out.println("Your new favorite color is: " + color);
}
//Function to ask if user wants to repeat this
public static void repeat()
{
//Variables
String response;
String color;
int slots;
System.out.println("Would you like to try again? (y/n) ");
response = ScottN_RecursionExcerise.myScanner.nextLine();
switch(response)
{
case "y":
{
System.out.println("Enter a number. ");
slots = Integer.parseInt(myScan.nextLine());
color = Search(slots);
System.out.println("Your new favorite color is: " + color);
System.out.println();
repeat();
}
case "n":
{
System.out.println();
menu();
}
default:
{
ScottN_RecursionExcerise.menuRedirect();
}
}
}
}
我创建此类的新实例,并在主类的菜单中开始算法。
//Create a new color instance
PickAColor pc = new PickAColor(13);
//Get user's resposne
pc.askUser();
System.out.println();
pc.repeat();
menu();
你知道我在做什么错吗?
答案 0 :(得分:0)
关于此代码可以说很多,但是您的特定问题的答案是Search方法应如下所示:
public static String Search(int num)
{
// Basic validation of 'num' omitted...
return colors[num];
}
您不需要循环数组,因为您知道要查找的颜色是数组中的索引编号。随便去吧:)