我希望将5个System.out.Print的每个输出存储在句子(x)变量中。另外,我想获取每个句子的最后一个单词(不包括标点符号)并将其设置为各自的变量。
public class WordGame
{
public static void main(String[] args)
{
//Sets up Scanner
Scanner in = new Scanner(System.in);
//Declares the Variables
int age;
String name;
String city;
String college;
String job;
String animal;
String petname;
//Get's the user input and assigns it to name
System.out.println("Enter a name: ");
name = in.next();
//Get's the user input and assigns it to age
System.out.println("Enter an age under 18: ");
age = in.nextInt();
//Get's the user input and assigns it to city
System.out.println("Enter your city: ");
city = in.next();
//Get's the user input and assigns it to college
System.out.println("Enter a name of a college: ");
college = in.next();
//Get's the user input and assigns it to job
System.out.println("Enter a profession: ");
job = in.next();
//Get's the user input and assigns it to animal
System.out.println("Enter an animal: ");
animal = in.next();
//Get's the user input and assigns it to petname
System.out.println("Enter a pet's name: ");
petname = in.next();
//Declares the Variables
String sentence1;
String sentence2;
String sentence3;
String sentence4;
String sentence5;
//Displays the Story using user inputs
System.out.println("There once was a person named " + name + " who lived in " + city + ".");
System.out.println("Even though " + name + " was only " + age + ", " + name + " went to college at " + college + ".");
System.out.println(name + " graduated and went to work as a " + job + ".");
System.out.println("Soon thereafter, " + name + " adopted a(n) " + animal + " named " + petname + ".");
System.out.println(name + " and " + petname + " both lived happily ever after!");
}
}
输出应类似于:“之后的(城市)(学院)(专业)(宠物)!”
例如“芝加哥耶鲁大学工程师Sparky之后!”
最佳答案
并不是很确定问题,而是直接将句子存储为变量,然后直接打印该变量,而不是立即打印该句子。然后您可以自由使用after变量。认为这可能会回答您的问题。
String sentence1 ="There once was a person named " + name + " who lived in " + city + ".";
String sentence2 = "Even though " + name + " was only " + age + ", " + name + " went to college at " + college + ".";
String sentence3 = name + " graduated and went to work as a " + job + ".";
String sentence4= "Soon thereafter, " + name + " adopted a(n) " + animal + " named " + petname + ".";
String sentence5 =name + " and " + petname + " both lived happily ever after!";
//Displays the Story using user inputs
System.out.println(sentence1);
System.out.println(sentence2);
System.out.println(sentence3);
System.out.println(sentence4);
System.out.println(sentence5);
如果要在打印后删除标点符号,可以执行以下操作:
sentence1 = sentence1.substring(0, str.length() - 1);
祝好运