java - 传递给方法的对象没有价值?
问题描述
我试图将 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?
解决方案
Scanner scanString = new Scanner(instruction);
这将创建一个Scanner
使用给定String
作为输入的。
next = new String(scanString.next());
这会根据扫描仪的分隔符读取输入,默认为空格。如果输入字符串不包含空格,则此调用将返回整个输入字符串。
注意:你永远不应该使用new String()
. 在这里你可以做到next = scanString.next()
。
推荐阅读
- javascript - 为什么我的 POST 请求不能在浏览器上运行,但它在邮递员中运行,即使我遵循相同的步骤/方式?
- jquery - Rails 6 Asset Pipeline:如何在 application.js 中导入供应商脚本?
- c# - 如何使用 AM/PM 提取日期时间值 && 从字符串中记住它的位置
- cmake - cmake 检查类中是否存在公共字段
- c++ - 语法错误:缺少';' 在 '*' 与 Item 类之前
- flutter - 如何在颤动中使用新的小部件更新页面?
- javascript - Discord bot 忽略所有 webhook?
- linux - crontab 删除路径包含 % 的文件
- sql - 根据另一个查询返回的值运行查询
- mysql - 从每天的特定时间选择一条数据 MySQL