【发布时间】:2015-05-23 05:11:11
【问题描述】:
目前,我的 Java 代码遇到了问题。我对 Java 有点陌生,所以如果你牢记这一点,我会很高兴的。
我的问题是将字符串值从一个类传递到另一个类。
主类:
private static void charSurvey()
{
characterSurvey cSObj = new characterSurvey();
cSObj.survey();
System.out.println();
}
第二:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class characterSurvey
{
public void survey(String character)
{
Scanner s = new Scanner(System.in);
int smartChina = 0,smartAmerica = 0,dumbAmerica = 0;
String answer;
System.out.println("Are you good with girls?");
System.out.println("y/n?");
answer = s.nextLine();
if(answer.equalsIgnoreCase("y"))
{
smartChina = smartChina - 3;
smartAmerica = smartAmerica + 2;
dumbAmerica = dumbAmerica + 4;
}
//...
//ASKING SEVERAL OF ABOVE ^
List<Integer> charSelect = new ArrayList<Integer>();
charSelect.add(smartChina);
charSelect.add(smartAmerica);
charSelect.add(dumbAmerica);
Collections.sort(charSelect);
Collections.reverse(charSelect);
int outcome = charSelect.get(0);
if(smartChina == outcome)
{
character = "smartChina";
}
else if(smartAmerica == outcome)
{
character = "smartAmerica";
}
else if(dumbAmerica == outcome)
{
character = "dumbAmerica";
}
System.out.println(character);
s.close();
}
}
当我调用第一个类时,我试图获取第二个类的值。
免责声明*此类中的字符串无意伤害任何人。这是我和中国室友之间的玩笑,谢谢。
【问题讨论】:
-
我建议用更通用的东西替换代码中任何可能令人反感的细节。至于在你的主类中获取字符串,你可以将你的
survey方法从void更改为String,然后return字符串。在你的主要课程中,你会做String data = survey()
标签: java string class parameters parameter-passing