【问题标题】:How to print multiple strings from a function in Java? [duplicate]如何从Java中的函数打印多个字符串? [复制]
【发布时间】:2021-06-12 05:54:35
【问题描述】:

我对学习 Java 非常陌生,所以我尝试制作一个非常基本的程序,其中有 2 个文本文档,一个包含 2,000 个名字,另一个包含 1,000 个姓氏。该程序将从每个中随机抽取一行并将其打印为一行。但是,我在尝试这样做时遇到了麻烦。这是代码。

import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.Random;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {

  private static Random first = new Random();
  private static Random second = new Random();
  private static int firstnumber = 0;
  private static int secondnumber = 0;
  private static String line1 = " ";
  private static String line2 = " ";

  public static void generateAnswers(){
      
      firstnumber = first.nextInt(999);
      firstnumber += 1;
      try{
        String line1 = Files.readAllLines(Paths.get("Firstnames.txt")).get(firstnumber);
      } 
      catch(IOException e){
        System.out.println(e);
      }

      secondnumber = second.nextInt(999);
      secondnumber += 1;
      try{
        String line2 = Files.readAllLines(Paths.get("Lastnames.txt")).get(secondnumber);
      }
      catch(IOException e){
        System.out.println(e);
      }
      System.out.println(line1 + " " + line2);
  }

  public static void main(String[] args) throws FileNotFoundException {
      generateAnswers();
  }

}

有谁知道我哪里出了问题以及如何解决它?

【问题讨论】:

  • 基本上,您正在打印 String line2 = " ";和 String line1=" " 因为您在 try 和 catch 中定义了另一个 String line2 和 line1。所以它们没有被分配任何值。
  • 你当前代码的输出是什么?

标签: java function variables


【解决方案1】:

原因是您的静态变量(如 line1line2)没有被赋值。您的问题在于这一行。您创建了另一个字符串,但没有为您的静态分配新值

String line1 = Files.readAllLines(Paths.get("Firstnames.txt")).get(firstnumber);

改变

String line1 = Files.readAllLines(Paths.get("Firstnames.txt")).get(firstnumber);

line1 = Files.readAllLines(Paths.get("Firstnames.txt")).get(firstnumber);

String line2 = Files.readAllLines(Paths.get("Lastnames.txt")).get(secondnumber);

 line2 = Files.readAllLines(Paths.get("Lastnames.txt")).get(secondnumber);

【讨论】:

    猜你喜欢
    • 2014-08-01
    • 1970-01-01
    • 2015-09-21
    • 2021-04-19
    • 2018-08-07
    • 2013-10-01
    • 2020-05-30
    • 1970-01-01
    • 2013-08-05
    相关资源
    最近更新 更多