这里的第一个问题,我搜索了很多关于将.length方法应用于用户输入的信息。不幸的是,所有已回答的问题都与我的情况无关。
我正在做一个有两个部分的学校项目。第一部分是滚动2个骰子,直到2个骰子的总和为7或11,然后打印一条消息,说明每个骰子滚动了什么,以及它们的总数。
作业的第二部分是我遇到麻烦的地方。我们应该让用户输入2个字符串,并让Java按字母顺序对2个字符串进行排序,然后使用.length显示两个字符串的长度,然后将它们加起来。我已经获得了用户输入的帮助,但是当我尝试计算字符串的长度时,它只是在方法末尾给了我返回字符串的长度。因此,当用户输入“ Hello”和“再见”时,我最终得到10和26,因为它计算的是“谢谢!”的长度。和“谢谢!现在收看!”我试过将.length放入'inputString'和'inputAnotherString'方法中,该方法无效。
import java.io.*;
import java.math.*;
public class Main {
public static void main(String[] args) throws IOException {
boolean keepRolling = true;
while (keepRolling) {
int dieOne = rollDice();
int dieTwo = rollDice();
int diceTotal = (dieOne + dieTwo);
if (diceTotal == 7 || diceTotal == 11) {
System.out.println("You rolled a " + dieOne + " and a " + dieTwo + ": total = " + diceTotal + ". You win!");
break;
} else {
System.out.println("You rolled a " + dieOne + " and a " + dieTwo + ": total = " + diceTotal + ". Roll again!");
}
}
String firstString;
firstString = inputString();
System.out.println(firstString);
String secondString;
secondString = inputAnotherString();
System.out.println(secondString);
int lengthOne = firstString.length();
System.out.println(lengthOne);
int lengthTwo = secondString.length();
System.out.println(lengthTwo);
int totalLength = lengthOne + lengthTwo;
System.out.println(totalLength);
}
public static int rollDice() {
return 1+ (int)(Math.random()*((6-1)+1));
}
public static String inputString() {
String stringOne;
BufferedReader in;
in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a string!");
try {
stringOne = in.readLine();
} catch(IOException e) {
}
return "Thank you!";
}
public static String inputAnotherString() {
String stringTwo;
BufferedReader in;
in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter another string!");
try {
stringTwo = in.readLine();
} catch(IOException e) {
}
return "Thank you! Now watch this!";
}
}
任何帮助将不胜感激!
答案 0 :(得分:0)
您的方法public static String inputString()
返回“谢谢!”而不是用户输入的内容。在这种情况下,通过设置一个调用firstString = inputString();
的变量,它将firstString设置为“谢谢!”。因此,调用firstString.length();
将返回“谢谢!”的长度。而不是用户提供的输入。
答案 1 :(得分:0)
您将变量分配给要调用的函数,这意味着它们已分配给那些函数的返回值。因此,firstString获取inputString()的返回值(在本例中为“谢谢!”)。您必须像这样在函数中返回输入的字符串:
public static String inputString() {
String stringOne;
BufferedReader in;
in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a string!");
try {
stringOne = in.readLine();
} catch(IOException e) {
}
return stringOne;
}
尽管您可能希望了解在这种情况下如何处理异常。