[英]Having trouble with Scanner class
I am using Scanner class to get a file name.我正在使用 Scanner 类来获取文件名。 But my Scanner s is not even asking me any string.
但是我的 Scanner s 甚至没有问我任何字符串。 It just set the entered string to ""(empty String).
它只是将输入的字符串设置为“”(空字符串)。 Then I get file not found exception.Also another question is, I am using FileOutputStream to write a file.
然后我得到文件未找到异常。另外一个问题是,我正在使用 FileOutputStream 来写一个文件。 Isn't it should create the file if not exists ?
如果不存在,是不是应该创建文件? Here is part of my code where I use scanner.
这是我使用扫描仪的代码的一部分。
else if(user_choice == 3){
System.out.println("kaydedilecek dosyanın ismini giriniz : ");
String file_name = s.nextLine();
IOdata iod = new IOdata(data);
iod.save_data(file_name);
and the below code is about io.下面的代码是关于 io.
public void save_data(String file_name) throws IOException {
try {
FileOutputStream fos = new FileOutputStream(file_name);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(data);
oos.close();
}catch (FileNotFoundException e){
file_name = "default";
FileOutputStream fos = new FileOutputStream(file_name);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(data);
oos.close();
}
}
Edit full of my Menu class:编辑完整的菜单类:
import java.io.IOException;
import java.util.Scanner;
public class Menu {
public Menu() throws IOException {
Scanner s = new Scanner(System.in);
Data data = new Data();
while(true){
System.out.println("1-data oluştur");
System.out.println("2-datayı yükle");
System.out.println("3-datayı kaydet");
System.out.println("4-çıkış");
System.out.println("5-yazdır");
int user_choice = s.nextInt();
if(user_choice == 4) {
break;
}else if(user_choice == 1){
DataManupilator dm = new DataManupilator(data);
System.out.println("datanın uzunluğunu giriniz : ");
int length = s.nextInt();
data = dm.generate_data(length);
}else if(user_choice == 5){
data.print_items();
}else if(user_choice == 3){
System.out.println("kaydedilecek dosyanın ismini giriniz : ");
String file_name = s.nextLine();
IOdata iod = new IOdata(data);
iod.save_data(file_name);
}else if(user_choice == 2){
System.out.println("datanın bulunduğu dosyanın ismini giriniz : ");
String file_name = s.nextLine();
IOdata iod = new IOdata(data);
iod.save_data(file_name);
}
}
}
}
There is some turkish Strings in my code so let me explain.我的代码中有一些土耳其字符串,所以让我解释一下。 If user chooses 3 program goes to write data to a file.
如果用户选择 3 个程序将数据写入文件。
试试这个输入选项int user_choice = Integer.parseInt(s.nextLine());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.