【发布时间】:2011-09-13 09:50:44
【问题描述】:
所以我和我的朋友在我们还是孩子的时候就尝试编写这个叫做 LOVERS 的小游戏。 其中写下2个人的名字,全名不加中间名,数名字中L、O、V、E、R、S的个数,加起来放在字母旁边。
示例:
名称 1:你好
名称 2:护理
左:2
O: 1
五:0
E:2
回复:1
S: 0
之后,您将成对添加它们。
示例:
左:2 > 3 > 4 > 7 > 15 > 32
O: 1 > 1 > 3 > 8 > 17
五:0 > 2 > 5 > 9
E: 2 > 3 > 4
R: 1 > 1
S: 0
事情是这样的……首先你添加前 2 个字母的值……LO 然后 OV 然后 VE 等等。直到你在这种情况下得到一个最终答案 32 .... 32 表示 2 人彼此兼容的百分比。
我知道它很愚蠢。哈哈,但我们只是为了好玩而尝试编程。我们是菲律宾的二年级 IT 学生。无论如何,我们想知道是否有办法递归地进行计算,以及是否有办法减少使用的数组数量。
这是我们的代码:
import java.util.*;
public class LOVERS {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
String name1="";
String name2="";
char love[] = {'L','O','V','E','R','S'};
int[] lovers = new int[6];
int[] temp= new int[6];
int[] temp2= new int[6];
boolean done = true;
while(done){
name1 = getName();
name2 = getName();
temp = getLetterCount(name1);
temp2 = getLetterCount(name2);
lovers = sumOfLetters(temp,temp2,love);
System.out.println("");
int[] firstLayer = new int[5];
int[] secondLayer = new int[4];
int[] thirdLayer = new int[3];
int[] fourthLayer = new int[2];
firstLayer = sums(lovers);
secondLayer = sums(firstLayer);
thirdLayer = sums(secondLayer);
fourthLayer = sums(thirdLayer);
int output = fourthLayer[0]+fourthLayer[1];
if(output>100){
output=100;
}
System.out.println("Result is : "+ output +"%");
System.out.println("Do you want to try again? Y/N :");
char again = ' ';
if(again == 'n')
{
done = false;
}
else done = true;
}
}
public static int[] sums (int[] y){
int[] x = new int[y.length-1];
for(int ctr=1;ctr<y.length;ctr++){
x[ctr-1]=y[ctr-1]+y[ctr];
}
return x;
}
public static String getName(){
String n="";
System.out.println("Enter name: ");
n = console.nextLine();
n = n.toUpperCase();
return n;
}
public static int[] sumOfLetters(int[] temp, int[] temp2, char[] love){
int[] lovers = new int[6];
for(int ctr=0;ctr<6;ctr++){
lovers[ctr]=temp[ctr]+temp2[ctr];
System.out.println(love[ctr]+" - "+lovers[ctr]);
}
return lovers;
}
public static int[] getLetterCount(String n){
int[] temp = new int[6];
for(int x=0;x<n.length();x++){
if(n.charAt(x)=='L'){
temp[0]++;
}
else if(n.charAt(x)=='O'){
temp[1]++;
}
else if(n.charAt(x)=='V'){
temp[2]++;
}
else if(n.charAt(x)=='E'){
temp[3]++;
}
else if(n.charAt(x)=='R'){
temp[4]++;
}
else if(n.charAt(x)=='S'){
temp[5]++;
}
}
return temp;
}
}
如您所见,我们使用 4 个数组进行 4 层计算,并使用循环语句进行计算。
那么这可以递归地完成吗?以及如何减少使用的数组数量?
这可以极大地帮助我们学习如何执行正确的递归函数,因为我们目前正在学习数据结构。希望你们能帮助我。谢谢
【问题讨论】: