使用.next()或.nextLine()的java字符串变量

使用.next()或.nextLine()的java字符串变量,java,Java,以下是我的源代码: package functiontest; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class FunctionTest { public static void main(String[] args) { Scanner

以下是我的源代码:

package functiontest;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class FunctionTest {

public static void main(String[] args) {
     Scanner scan = new Scanner(System.in);
    int option;
    String cname, cpassword="testpassword",chp="010-000000";

//        cname="clerk test";

    System.out.println("1. add");
    System.out.println("2. delete");
    option = scan.nextInt();
    switch(option)
    {
        case 1:
            System.out.print("Enter clerk name:\t");
            cname = scan.nextLine();
            File cfile = new File("clerk/"+cname+".txt");
               FileWriter cwrite;
               try
               {
                   cwrite = new FileWriter(cfile);
                   BufferedWriter cbuf = new BufferedWriter(cwrite);
                   cbuf.write("clerk name:\t" +cname);
                   cbuf.write("clerk password:\t"+cpassword);
                   cbuf.write("clerk handphone number:\t"+chp);
                   cbuf.flush();
                   cbuf.close();
                   System.out.println("The clerk profile create completely");
               }catch(IOException e)
               {
                   System.out.println("Error! clerk profile cannot create");
               }
            ;break;
        case 2:
            String dclerk;
//                dclerk = "clerk test";
                System.out.print("\nPlease enter clerk name for delete:\t");
                dclerk = scan.next();
                File dcfile = new File("clerk/"+dclerk+".txt");
                if(!dcfile.exists()) 
                {
                    System.out.println("Error! the clerk profile not exist");
                }
                try
                {
                    dcfile.delete();
                    System.out.println(dclerk + "'s prifle successful delete");
                }catch(Exception e)
                {
                    System.out.println("Something wrong! " + dclerk +" profile cannot delete");
                    };break;
        }
    }
}
我无法输入变量名cname

        cname = scan.nextLine()
当我运行程序时,它会显示如下结果:

run:
1. add
2. delete
1
Enter clerk name:   The clerk profile create completely
当我使用
.next():

它无法读取该文件

cname
例如,使用空格

clerk test 
它会读

clerk 

只有我该怎么办?

你的问题是线路不通

option = scan.nextInt();
不读取整数后的新行字符。因此,当您稍后执行
nextLine()
时,新行最终被读取

要解决此问题,您应该添加一个额外的

scan.nextLine()
调用
nextInt()
后,使用

cname = scan.nextLine();

当你想读职员的名字时。

@DavidWallance非常感谢。它解决了我的问题,我可以添加和删除
cname = scan.nextLine();