Java 当我有空格时出现 MisMatchException

Java MisMatchException when I have a whitespace

我有一个问题 case 9 我想在我的代码中写点东西。当我写一个 String 而没有像 ("huhuu") 这样的白色 space 时,它会写入我的文件。但是当我输入一个包含白色 space 的 String 时,例如 "Hey you",它 returns 一个例外:

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:864)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextInt(Scanner.java:2117)
    at java.util.Scanner.nextInt(Scanner.java:2076)
    at assignment3.Main.main(Main.java:60)
C:\Users\Nigel Andam\AppData\Local\NetBeans\Cache.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 15 seconds)

现在我有这个代码

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package assignment3;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
import java.util.Scanner;


/**
 *
 * @author Nigel Andam
 */
public class Main {

    /**
     * @param args the command line arguments
     */

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);    

        int choice;
        do {
        System.out.println("");
        System.out.println("Please choose an option: \n"
                + "[1] - create Directory \n"
                + "[2] - create Multiple Directory \n"
                + "[3] - create File \n"
                + "[4] - rename a  File/Directory \n"
                + "[5] - copy a File/Directory \n"
                + "[6] - move a File/Directory \n"
                + "[7] - hide a File/Directory \n"
                + "[8] - unhide a File/Directory \n"
                + "[9] - write a Text File \n"
                + "[10] - read a Text File \n"
                + "[0] - exit");    
            System.out.println();
        choice = sc.nextInt();
        switch (choice) {
            case 1:
                CreateDirectory cd = new CreateDirectory();
                String directory = null;
                System.out.print("Enter Path: ");
                directory = sc.next();
                Path path = Paths.get(directory);
                if(isValidPath(directory)) {
                     cd.createDirectory(path.toString());
                }else {
                    System.out.println(path.toString() + " is valid? " + isValidPath(path.toString()));
                }
                break;
            case 2:
                CreateMultipleDirectory mcd = new CreateMultipleDirectory();
                String directory2 = null;
                System.out.print("Enter Path: ");
                directory2 = sc.next();
                Path path2 = Paths.get(directory2);
                if(isValidPath(directory2)) {
                    mcd.createMulipleDirectory(directory2);
                }else {
                    System.out.println(path2.toString() + " is valid " + isValidPath(path2.toString()));
                }
                break;
            case 3:
                CreateFile cf = new CreateFile();
                String directory3 = null;
                System.out.print("Enter Path: ");
                directory3 = sc.next();
                Path path3 = Paths.get(directory3);
                if(isValidPath(directory3)) {
                    String fileName, extensionFile = null;
                    System.out.print("Filename first: ");
                    fileName = sc.next();
                    System.out.print("Extension File: ");
                    extensionFile = sc.next();
                    cf.createFile(path3.toString(), fileName, extensionFile);
                }else {
                    System.out.println(path3.toString() + " is valid " + isValidPath(path3.toString()));
                }
                break;

            case 4:
                RenameDirectoryFile rdf = new RenameDirectoryFile();
                String directory4 = null;
                System.out.print("Enter Path: ");
                directory4 = sc.next();
                File src = new File(directory4);
                Path path4 = Paths.get(directory4);
                if(isValidPath(directory4)) {
                    System.out.print("New filename: ");
                    String newFileName = sc.next();
                    rdf.rename(src, newFileName);
                }else {
                     System.out.println(path4.toString() + " is valid " + isValidPath(path4.toString()));
                }
                break;
            case 5:
                CopyFile ccf = new CopyFile();
                String source, destination = null;
                System.out.print("Enter Path: ");
                source = sc.next();
                System.out.print("Destination where to copy: ");
                destination = sc.next();
                Path path11 = Paths.get(source);
                Path path12 = Paths.get(destination);
                if(isValidPath(source) && isValidPath(destination)) {
                    File src2 = new File(source);
                    File dest = new File(destination);
                    ccf.copyFile(src2, dest);
                }else {
                    System.out.println(path11.toString() + " is valid " + isValidPath(path11.toString()));
                    System.out.println(path12.toString() + " is valid " + isValidPath(path12.toString()));
                }
                break;
            case 6:
                MoveFile mf = new MoveFile();
                String source2, destination2 = null;
                System.out.print("Enter Path: ");
                source2 = sc.next();
                System.out.print("Destination where to move: ");
                destination2 = sc.next();
                Path path13 = Paths.get(source2);
                Path path14 = Paths.get(destination2);
                if(isValidPath(source2) && isValidPath(destination2)) {
                    File src3 = new File(source2);
                    File dest2 = new File(destination2);
                    mf.move(src3, dest2);
                }else {
                    System.out.println(path13.toString() + " is valid " + isValidPath(path13.toString()));
                    System.out.println(path14.toString() + " is valid " + isValidPath(path14.toString()));
                }
                break;
            case 7:
                HideFile hf = new HideFile();
                String directory5 = null;
                System.out.print("Enter Path: ");
                directory5 = sc.next();
                Path path6 = Paths.get(directory5);
                if(isValidPath(directory5)) {
                    hf.hideFile(directory5);
                }else {
                    System.out.println(path6.toString() + " is valid " + isValidPath(path6.toString()));
                }
                break;
            case 8:
                UnHideFile uhf = new UnHideFile();
                String directory6 = null;
                System.out.print("Enter Path: ");
                directory6 = sc.next();
                Path path7 = Paths.get(directory6);
                if(isValidPath(directory6)) {
                    uhf.unHideFile(directory6);
                }else {
                    System.out.println(path7.toString() + " is valid " + isValidPath(path7.toString()));
                }
                break;
            case 9:

                String directory7 = null;
                System.out.print("Enter Path: ");
                directory7 = sc.next();
                Path path8 = Paths.get(directory7);
                if(isValidPath(directory7)) {
                System.out.print("Filename: ");
                String fileName = sc.next();
                System.out.println("Extension File: ");
                String extension = sc.next();
                File file = new File(directory7 + "\" + fileName + extension); 
                    if(!file.exists()) {
                        Path path10 = Paths.get(directory7);             
                        CreateFile cf2 = new CreateFile();
                        cf2.createFile(path10.toString(), fileName, extension);
                        String write;
                        System.out.print("Write something");
                        write = sc.next();
                        WriteFile wf = new WriteFile("Hello World");
                        wf.writeFile(file);
                      }
                }else {
                    System.out.println(path8.toString() + " is valid " + isValidPath(path8.toString()));
                }    
                break;
            case 10:
                String directory8 = null;
                System.out.print("Enter Path: ");
                directory8 = sc.next();
                Path path10 = Paths.get(directory8);
                File f3 = new File(path10.toString());
                if(isValidPath(directory8)) {
                    ReadFile rf = new ReadFile();
                    rf.readFile(f3);
                }else {
                     System.out.println(path10.toString() + " is valid " + isValidPath(path10.toString()));
                }
                break;
            case 0:

                break;
            default:
                System.out.println("Invalid Option");
                break;
        }
        }while (choice !=0);
    }
      public static boolean isValidPath(String path) {
            try {
                Paths.get(path);
            } catch (InvalidPathException e) {
                System.err.println(e);
                return false;
            }
            return true;
        }
    }

WriteFileclass

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package assignment3;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;


/**
 *
 * @author Nigel Andam
 */
public class WriteFile {
    private String write;
    public WriteFile(String write) {
//        System.out.println("WRITE FILE");
        this.write = write;
    }
    public String getWrite() {
        return write;
    }
     public void writeFile(File file) {
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(file);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
            bufferedWriter.write(getWrite());
//            bufferedWriter.newLine();// append a newline character.
//            bufferedWriter.write("writing text after newline");
            bufferedWriter.close();// Always close files.
        } catch (IOException ex) {
            System.out.println("Unable to write file '" + file.getAbsolutePath() + "'");
        } finally {
            try {
                fileWriter.close();
            } catch (IOException ex) {
                System.err.println(ex);
            }
        }
    }
}

当你只需要来自用户的字符串时,我会抓取整行输入。将所有 sc.next() 替换为 sc.nextLine()。然后创建一个从用户那里获取整数输入的函数,并将所有出现的 sc.nextInt() 替换为您的函数调用。

public static int getNumberFromUser(Scanner scan)
{
    boolean userEnteredNumber = false;
    while(!userEnteredNumber)
    {
        System.out.println("Please enter a number: ");
        String inputFromUser = scan.nextLine();
        if(inputFromUser.matches("\d+"))
        {
            return Integer.parseInt(inputFromUser);
        }
        else
            System.out.println("Input Not an Integer - " + inputFromUser);
    }
    return 0;
}

现在,当您想从用户那里获取号码而不是像这样使用 nextInt() 时调用此方法

choice = getNumberFromUser(sc);