文件输出流没有创建另一个文件[重复]。

问题描述 投票:0回答:1

我试图让我的程序创建另一个文件,可以由用户命名,并打印出用户想要打印的随机数字。不幸的是,当我运行我的程序时,它一直工作到最后 "你想使用什么文件名",其中程序指出

"File not found java.io.FileNotFoundException: (句柄无效)"

我想知道怎样才能让程序实际创建文件,并让用户为文件选择自己的名字。

import java.io.*;
import java.util.*;

public class chooseRandNum{
    public static void main(String[] args){
        Random rand = new Random();
        Scanner key = new Scanner(System.in);
        System.out.println("How many random numbers do you want? ");
        int totalRand = key.nextInt();
        System.out.println("What is the smallest random number? ");
        int smallRand = key.nextInt();
        System.out.println("What is the largest random number? ");
        int largeRand = key.nextInt();
        System.out.println("What filename do you want to use? ");
        String fname = key.nextLine();

        File outputFile = new File(fname);
        PrintStream outputStream = null;

        try{
            outputStream = new PrintStream(outputFile);
        }

        catch (Exception e){
            System.out.println("File not found " + e);
            System.exit(1);
        }

        int n = rand.nextInt(largeRand - smallRand + 1);
        for(int i = 0; i <= 5; i++){
            for(int j = 0; j <= totalRand; j++){
                outputStream.print(n + ",");
            }
            outputStream.println();
        }   
    }
}
java output java.util.scanner printwriter
1个回答
1
投票

String fname = key.nextLine(); 应该是 String fname = key.next();

代码还有其他问题,但这解决了问题中的问题。

从JavaDoc:

nextLine()

/**
 * Advances this scanner past the current line and returns the input
 * that was skipped.
 *
 * This method returns the rest of the current line, excluding any line
 * separator at the end. The position is set to the beginning of the next
 * line.
 *
 * <p>Since this method continues to search through the input looking
 * for a line separator, it may buffer all of the input searching for
 * the line to skip if no line separators are present.
 *
 * @return the line that was skipped
 * @throws NoSuchElementException if no line was found
 * @throws IllegalStateException if this scanner is closed
 */

next()

/**
 * Finds and returns the next complete token from this scanner.
 * A complete token is preceded and followed by input that matches
 * the delimiter pattern. This method may block while waiting for input
 * to scan, even if a previous invocation of {@link #hasNext} returned
 * {@code true}.
 *
 * @return the next token
 * @throws NoSuchElementException if no more tokens are available
 * @throws IllegalStateException if this scanner is closed
 * @see java.util.Iterator
 */

0
投票

在这些语句之后

System.out.println("What is the largest random number? ");
int largeRand = key.nextInt();

把这个

key.nextLine(); // clear lingering new line

然后继续。


System.out.println("What filename do you want to use? ");
String fname = key.nextLine();

并在这个网站上查看以下内容: 扫描仪的使用

© www.soinside.com 2019 - 2024. All rights reserved.