程序本身应该接受用户输入,然后在 Mad Lib 的制作过程中将其读取。用户输入名词、动词、形容词等,然后以故事的形式将其全部打印到控制台。
import java.util.Scanner;
public class CSFacts {
//first method
public static String Noun(int on) { //Start first user input, start with noun
String noun1;
Scanner input=new Scanner(System.in);
while (on==1) {
System.out.println("Please enter a Noun."); //prompt user to input a noun to be used in the main program
noun1=input.nextLine();
on=on-1;}
while (on==0) {
noun1=input.nextLine(); }
return noun1;
//return the noun as a string to be used in the main program
}
public static void main(String[] args) {
Noun(1);
System.out.println("Be kind to your "+Noun(0));
}
我面临的问题是 noun1 不会与我合作,因为它不会从一个参数传递到另一个参数。我需要 noun1 从 on=1 到 on=0,这样当第二次调用该方法时,它会显示“善待你的(插入 noun1)”。我似乎不知道如何把它带过去。这只是我实验室的一部分,但如果我能弄清楚如何做到这一点,我可以将其融入到我的其他方法中。
最佳答案
你似乎有一个无限循环:
while (on==0) {
noun1=input.nextLine(); }
您使用 Noun(1)
调用您的方法,因此 on
为 1。您的第一个循环将运行一次,然后结束,设置 on
> 到 0。然后你的第二个循环将永远运行,因为它永远不会改变 on
,但会一直运行直到它被改变,而这永远不会发生。
为了回答您的实际问题,noun1
是在方法 Noun()
中定义的,因此它是一个局部变量,不能在其他任何地方使用。要解决这个问题,您可以将其定义为 Noun()
外部的静态变量,如下所示:
static String noun1;
另一种选择是在主方法中使用从 Noun()
返回的值,而不是像您所做的那样丢弃它:
String noun1 = Noun(1);
关于java - 如何在 while 循环中、while 循环之外、方法内部的所有 while 中访问字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28868461/