java - Java 属性:如何连续更新两个关键字?
问题描述
我有一段用于更新属性文件的基本代码。但是,似乎在两个可能要更新的关键字中,只有第二个是由用户输入更新的,而不是一个接一个地更新。
这是完整的代码:
import java.io.*;
import java.util.Properties;
import java.util.Scanner;
public class UpdateProperty{
private static int choice;
static Scanner sc = new Scanner(System.in);
public static void main(String args[]) throws Exception
{
FileInputStream in = new FileInputStream("Stats.properties");
Properties props = new Properties(); //creates a Properties object named prop
props.load(in); //loads in as value of prop
in.close(); //no idea
System.out.println("1- BlackBerryIzzie: " + props.getProperty("BlackBerryIzzie"));
System.out.println("2- GrapeFruitIzzie: " + props.getProperty("GrapeFruitIzzie"));
System.out.println("");
String blackAmount = props.getProperty("BlackBerryIzzie");
String grapeAmount = props.getProperty("GrapeFruitIzzie");
//System.out.println("Selling BlackBerry Izzie");
//blackAmount = itemSold(blackAmount);
System.out.println("Do you wish to update inventory? Type 2");
choice = sc.nextInt();
if (choice == 2){
FileOutputStream out = new FileOutputStream("Stats.properties");
System.out.println("Insert BlackBerry Amount");
blackAmount = sc.nextLine();
props.setProperty("BlackBerryIzzie", blackAmount);
System.out.println("Insert GrapeFruit Amount");
grapeAmount = sc.nextLine();
props.setProperty("GrapeFruitIzzie", grapeAmount);
props.store(out, null);
out.close();
}
}
public static String itemSold(String s){
int i=Integer.parseInt(s);
i -= 1;
String ret=Integer.toString(i);
return ret;
}
}
似乎出现故障的位:
if (choice == 2){
FileOutputStream out = new FileOutputStream("Stats.properties");
System.out.println("Insert BlackBerry Amount");
blackAmount = sc.nextLine();
props.setProperty("BlackBerryIzzie", blackAmount);
System.out.println("Insert GrapeFruit Amount");
grapeAmount = sc.nextLine();
props.setProperty("GrapeFruitIzzie", grapeAmount);
props.store(out, null);
out.close();
}
这意味着向用户询问黑莓数量,然后将 BlackBerryIzzie 关键字更新为该数量。然后,它意味着在黑莓完成后对葡萄柚做同样的事情。然而,它会跳过黑莓,只要求一个扫描仪输入并将葡萄柚设置为那个。谢谢你的时间!
解决方案
不要混用nextLine
和nextAnythingElse
。
解决方案是将扫描仪的分隔符设置为您想要的。您当然希望“用户按下回车”作为分隔符。所以,告诉扫描仪。scanner.useDelimiter("\\R")
制作完成后立即运行。然后,要获得“整行”, call .next()
,如果您希望将该行读取为例如 int , call.nextInt()
等。不要要求nextLine()
任何东西。
解释为什么混合 nextLine 和 nextAnythingElse 不好是一个故事 -这个 SO 答案解释了其中的一部分。不幸的是,1000 票接受的答案不是正确的解决方案(.useDelimiter("\\R")
然后.next()
阅读一行是正确的解决方案)。
推荐阅读
- javascript - 在 Promise.all 中使用 .map
- java - SpringBoot WebTestClient - 如何在 graphql API 中使用 expectBody
- java - 读取 RequestMapping 注解值
- java - Java 中的 Envoy gRPC HTTP/1.1 桥接器
- c - C中的三元运算符
- excel - 在 VBA 中使用 LinEst 处理多线性多项式
- node.js - 为什么我的 React + NodeJS 在本地网络上无法访问?
- javascript - PROTRACTOR - 元素未附加到页面文档
- unity3d - 如何修复 Unity 3D 动画器窗口错误?
- python - 如何在 python 中加速 Elasticsearch 滚动