java - 如何在此程序中仅使用两个字符串?

标签 java string readline readlines

我的老师给了我这个问题:

Write a program that does the following:

  • Enter your first name: Peter
  • Enter your last name: Opunga
  • Enter your birth year: 1992
  • Hi Peter Opunga, you will be 20 by the end of this year.
  • Bonus 1: Proper commenting. (10%)
  • Bonus 2: Create only 2 Strings in the entire program. (10%)
  • Bonus 3: Use exactly 4 System.out.print. (10%)

现在我对 Java 完全陌生。一个多星期前我才被介绍到它,这就是我的想法:

import java.io.*;

public class A1Chuah {

    public static void main(String[] args) throws IOException {

        BufferedReader in = new BufferedReader (new InputStreamReader (System.in));

        //Prints instructions for user to enter first name.
        System.out.println("Enter first name: ");
        //Obtains user input for first name.
        String first = in.readLine ();
        //Prints instructions for user to enter last name.
        System.out.print ("Enter last name: ");
        //Obtains user input for last name.
        String last = in.readLine();
        //Prints instructions for user to enter birth year.
        System.out.print ("Enter your birth year: ");
        //Obtains user input for birth year.
        String year = in.readLine ();
        //Converts String year to int useryr
        int useryr = Integer.parseInt(year);
        //Sets int oriyr to value of 2012
        int oriyr = 2012;
        //Sets int outyr as oriyr - useryr
        int outyr = oriyr - useryr;
        //Prints out information.
        System.out.println("Hi" + " " + " " + last + "," + " " + "you will be" +  " " + outyr + " " + "by the end of this year");

我已经成功完成了奖励 1 和 3,但似乎无法弄清楚奖励 2。请帮忙! 附:他说只要我不冒充自己的想法,我就能得到帮助。

最佳答案

您可以使用一个字符串来获取全名,并使用一个字符串来获取年份。 你可以这样做

    System.out.println("Enter first name: ");

    String name = in.readLine();

    System.out.print ("Enter last name: ");

    name+= " " + in.readLine();

    System.out.println(name); // should print first and last

关于java - 如何在此程序中仅使用两个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9322029/

相关文章:

string - 使用 trie 进行字符串分割 - 时间复杂度?

java - 在 Java 中逐行读取文本文件的最快方法

c - ANSI C getc 在 Linux 而不是 OS X 上导致段错误

java - 读取要设置的行

java - Spring Rest `@Controller` 扭曲行为

java - 为什么我无法获取 Failfast 事件和 ConcurrentModificationException

java - 打开 Excel 时,apache POI createFormulaListConstraint 结果为 "Unreadable content"

java - 我自己的 Maven 插件如何获取 Maven Artifact 的可用版本?

c - 无法在 C 中按字母顺序对字符串列表进行排序

string - Terraform 将元组展平为字符串集