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

时间:2015-12-15 16:20:02

标签: java

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

我遇到的问题是,如果用户选择了特定的号码,我试图让程序打印整个.txt文件,在这种情况下,' 1'。我目前的代码是:

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声明完全关闭了,而且我朝着错误的方向前进,有人能指出我在右边并帮助我吗?

3 个答案:

答案 0 :(得分:2)

你关闭了,但并不完全。

您正确读取用户输入,但现在需要循环播放文件内容。

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

只要文件内容hasNextLine

,就会继续查看

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

另外,只是一小部分命名约定,不要使用全部大写字母作为变量名称,除非它们是静态的。此外,变量的第一个字母通常是小写的。

答案 1 :(得分:2)

  if (S.nextInt() == 1) {
    // check if there is input ,if true print it
    while((INPUT.hasNextLine())
            System.out.println(INPUT.nextLine());

     }

答案 2 :(得分:0)

此外,对于这样的菜单方案,请考虑使用switch语句,然后在默认情况下调用菜单打印(移动到单独的方法),这样如果输入错误,您可以重新打印菜单选项。此外,switch语句比一堆if更具可读性(可以说是),如下所示:

int option = S.nextInt();

    switch(option) {
        case 1 : 
            while(INPUT.hasNextLine()) {
                System.out.println(INPUT.nextLine());
            }
           break; 

        case 2 :
            //Do stuff
            break; 

        default :
            //Default case, reprint menu?

    }
}
相关问题