首页 > 解决方案 > 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 关键字更新为该数量。然后,它意味着在黑莓完成后对葡萄柚做同样的事情。然而,它会跳过黑莓,只要求一个扫描仪输入并将葡萄柚设置为那个。谢谢你的时间!

标签: java

解决方案


不要混用nextLinenextAnythingElse

解决方案是将扫描仪的分隔符设置为您想要的。您当然希望“用户按下回车”作为分隔符。所以,告诉扫描仪。scanner.useDelimiter("\\R")制作完成后立即运行。然后,要获得“整行”, call .next(),如果您希望将该行读取为例如 int , call.nextInt()等。不要要求nextLine()任何东西。

解释为什么混合 nextLine 和 nextAnythingElse 不好是一个故事 -这个 SO 答案解释了其中的一部分。不幸的是,1000 票接受的答案不是正确的解决方案(.useDelimiter("\\R")然后.next()阅读一行是正确的解决方案)。


推荐阅读