使用.next()或.nextLine()的java字符串变量 [英] java string variable using .next() or .nextLine()
本文介绍了使用.next()或.nextLine()的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 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;
}
}
}
我无法输入变量name cname
i cannot the enter the variable name cname
cname = scan.nextLine()
当我运行程序时,它显示如下结果:
when i run the program it show the result as below:
run:
1. add
2. delete
1
Enter clerk name: The clerk profile create completely
当我使用 .next()时:
cname = scan.next()
它无法读取
cname
带空格,示例
clerk test
它会读取
clerk
我该怎么做?
推荐答案
你的问题是该行
option = scan.nextInt();
在整数后不读取新行字符。因此,当您稍后执行 nextLine()
时,最终会读取新行。
does not read the new line character after the integer. So that new line is finally read when you do nextLine()
, later on.
要解决此问题,您应该添加额外的
To fix this, you should add an extra
scan.nextLine()
调用 nextInt()
,然后使用
cname = scan.nextLine();
当你想要阅读职员的名字时。
when you want to read the clerk's name.
这篇关于使用.next()或.nextLine()的java字符串变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文