我目前正在尝试创建一个小程序,将食谱创建为csv文件。直到我想要添加一个在中间带有空格的“成分”为止,效果都很好:“真正的大香蕉”。每当我写这样的东西,带下划线或带负号的东西时,它都会输入null而不是我写的单词。 我有一个类的成分(双量,字符串单位,字符串成分,字符串标签)与所有变量的getter和setters。 我创建csv的代码
public static ArrayList<Ingredients> createIngredientList() {
Scanner scan = new Scanner(System.in);
ArrayList<Ingredients> list = new ArrayList<Ingredients>();
char quit = 'Y';
String unit, ingredient, tags;
double amount;
while(quit == 'Y') {
System.out.print("Please use underscores instead of spaces e.g. real_big_boats.\n");
System.out.print("Amount: ");
amount = scan.nextDouble();
System.out.print("Unit: ");
unit = scan.next();
System.out.print("Ingredient: ");
ingredient = scan.nextLine();
System.out.print("Tags (e.g. tag;tag;tag): ");
tags = scan.nextLine();
list.add(new Ingredients(amount, unit, ingredient, tags));
System.out.print("More Ingredients? (Y/N) ");
String s = scan.next();
s = s.toUpperCase();
quit = s.charAt(0);
}
return list;
}
您可以在下面的我的pastebin中找到整个课程。 https://pastebin.com/vi09kGqi
答案 0 :(得分:1)
while (quit == 'Y') {
System.out.print("Please use underscores instead of spaces e.g. real_big_boats.\n");
System.out.print("Amount: ");
amount = scan.nextDouble();
scan.nextLine() ;
System.out.print("Unit: ");
unit = scan.next();
scan.nextLine() ;
System.out.print("Ingredient: ");
ingredient = scan.findInLine("(\\s|\\S)*");
scan.nextLine() ;
System.out.print("Tags (e.g. tag;tag;tag): ");
tags = scan.next();
scan.nextLine() ;
list.add(new Ingredients(amount, unit, ingredient, tags));
System.out.print("More Ingredients? (Y/N) ");
String s = scan.next();
scan.nextLine() ;
s = s.toUpperCase();
quit = s.charAt(0);
}
答案 1 :(得分:0)
这是由于Java中Scanner的一个已知问题。在此处查看链接:Scanner is skipping nextLine() after using next() or nextFoo()?
您可以在每个scanner.nextDouble()或scanner.next()之后使用空白的scanner.nextLine()来解决此问题。
public static ArrayList<Ingredients> createIngredientList() {
Scanner scan = new Scanner(System.in);
ArrayList<Ingredients> list = new ArrayList<Ingredients>();
char quit = 'Y';
String unit, ingredient, tags;
double amount;
while(quit == 'Y') {
System.out.print("Please use underscores instead of spaces e.g. real_big_boats.\n");
System.out.print("Amount: ");
amount = scan.nextDouble();
scan.nextLine();
System.out.print("Unit: ");
unit = scan.next();
scan.nextLine();
System.out.print("Ingredient: ");
ingredient = scan.nextLine();
System.out.print("Tags (e.g. tag;tag;tag): ");
tags = scan.nextLine();
list.add(new Ingredients(amount, unit, ingredient, tags));
System.out.print("More Ingredients? (Y/N) ");
String s = scan.next();
s = s.toUpperCase();
quit = s.charAt(0);
}
return list;
}
输出:
Please use underscores instead of spaces e.g. real_big_boats.
Amount: 111
Unit: 111
Ingredient: a b c
Tags (e.g. tag;tag;tag): a b c
More Ingredients? (Y/N) N
Ingredients [amount=111.0, unit=111, ingredient=a b c, tags=a b c]
另一种解决方案是通过使用Scanner.nextLine()将每个输入作为String接受,然后将其解析为所需的类型。