gpt4 book ai didi

java - 根据用户输入打印文件内容

转载 作者:行者123 更新时间:2023-11-30 06:56:33 25 4
gpt4 key购买 nike

尝试根据标题中提到的用户输入打印文件。基本上,我的程序已从我之前创建的从文件中读取数据的程序进行了更改,因此我知道该文件已正确导入(不是问题所在)。

我遇到的问题是,如果用户选择特定数字(在本例中为“1”),我试图让程序打印整个 .txt 文件。到目前为止,我当前的代码是:

import java.io.FileReader;
import java.util.Scanner;

public class InputOutput {
public static void main(String[] args) throws Exception {
// these will never change (be re-assigned)
final Scanner S = new Scanner(System.in);
final Scanner INPUT = new Scanner(new FileReader("C:\\Users\\JakeWork\\workspace\\Coursework\\input.txt"));

System.out.print("-- MENU -- \n");
System.out.print("1: Blahblahblah \n");
System.out.print("2: Blahblahblah \n");
System.out.print("Q: Blahblahblah \n");
System.out.print("Pick an option: ");

if (S.nextInt() == 1) {
String num = INPUT.nextLine();
System.out.println(num);
}

我感觉好像我的 if 语句完全错误,我正朝着完全错误的方向前进,谁能指出我正确的方向并伸出援助之手?

最佳答案

你很接近,但还不够。

您正确地读取了用户输入,但现在您需要循环中的文件内容。

if(S.nextInt() == 1) {
while (INPUT.hasNextLine()) {
System.out.println(INPUT.nextLine());
}
}

只要文件内容 hasNextLine

就会一直查找

您可以安全地删除 String option = S.next();

此外,只是对命名约定挑剔一点,变量名不要全部使用大写字母,除非它们是静态的。此外,变量的第一个字母通常是小写的。

关于java - 根据用户输入打印文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34294227/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com