首页 > 解决方案 > 传递给方法的对象没有价值?

问题描述

我试图将 Scanner 对象传递给方法create()但在方法内部 Scanner 对象没有任何值。如果有人有任何提示,这是代码:

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

public final class Instructions
{
    /**
     * Make constructor private so that there cannot be 
     * any instances of the class.
     */
    private Instructions(){}


    public static void operate(String instruction)
    {
        //Get instruction
        Scanner scanString = new Scanner(instruction);
        scanString.useDelimiter(" |;");
        String next;

        //Scan and operate
        if(scanString.hasNext())
        {
            next = scanString.next();

            if(next.equals("CREATE"))
            {
                create(scanString);
            }
            else if(next.equals(".EXIT"))
            {
                System.exit(0);
            }   
        }

        scanString.close();
    }

    private static void create(Scanner scanString)
    {
        //Program reaches here with what should be "DATABASE db_1"
        //left in scanString

        String next;

        if(scanString.hasNext())
        {
            System.out.println("HERE"); //Never reaches this

            next = scanString.next();

            if(next.equals("DATABASE"))
            {
                createDatabase(scanString);
            }
            else if(next.equals("TABLE"))
            {
                createTable(scanString);
            }
            else
            {
                System.out.println("Instruction " + next + " not recognized. Skipping instruction." );
            }
        }
    }

    private static void createDatabase(Scanner scanString)
    {
        File database;

        if(scanString.hasNext())
        {
            database = new File(scanString.next());

            if(!database.exists())
            {
                //Make a database file
                try
                {
                    database.createNewFile();
                }
                catch(IOException e)
                {
                    e.printStackTrace();
                }
            }
            else
            {
                System.out.println("!Failed to create database " + database.toString() + 
                    "because it already exists.");
            }
        }
    }

    private static void createTable(Scanner scanString)
    {

    }
}

我正在读取的输入文件具有以下形式:

CREATE DATABASE db_1;

我试图弄清楚为什么当我在 create() 方法中调用 scanString.hasNext() 时,当第一个分隔符之后还有两个标记时,scanString.hasNext() 没有返回 true?

标签: javajava.util.scannerdatabase-cursor

解决方案


Scanner scanString = new Scanner(instruction);

这将创建一个Scanner使用给定String作为输入的。

next = new String(scanString.next());

这会根据扫描仪的分隔符读取输入,默认为空格。如果输入字符串不包含空格,则此调用将返回整个输入字符串。

注意:你永远不应该使用new String(). 在这里你可以做到next = scanString.next()


推荐阅读