【问题标题】:Need my program to know where I left off需要我的程序知道我离开的地方
【发布时间】:2023-03-14 23:39:01
【问题描述】:

所以我正在尝试制作剪辑卡应用程序。换句话说,我正在制作一个应用程序来计算客户购买了多少咖啡,并且每购买 10 次咖啡,客户就会获得一份免费咖啡。我已经完成了循环,但我很难弄清楚如何让我的程序记住我离开的地方。例如,假设我已经购买了第 7 杯咖啡并且要离开,所以我想关闭应用程序;有没有办法让程序记住下次运行时从哪里继续?

这是我目前所拥有的:

import java.util.Scanner;

public class FelixNeww {

public static void main(String [] args) {
    Scanner key;
    String entry;
    int count = 0;
    String password = "knusan01";
    while(true) {
        System.out.println("Enter password: ");
        key = new Scanner(System.in);
        entry = key.nextLine();
        if(entry.compareTo(password) == 0){
            count++;
            System.out.println("You're one step closer to a free coffe! You have so far bought " 
            + count + " coffe(s)");
        }
        if(count == 10  && count != 0){
            System.out.println("YOU'VE GOT A FREE COFFE!");
            count = 0;
        }
        if(entry.compareTo(password) != 0){
            System.out.println("Wrong password! Try again.\n");
        }
    }
}

}

谢谢

【问题讨论】:

  • 坚持就是这个词。您可以使用数据库来存储信息。
  • 写入文件并将其存储在您的硬盘上。我认为我们不需要为此使用数据库。
  • 其他 cmets,您不必比较 count == 10 && count != 0,只需 count == 10。您也可以使用 entry.equals(password)。你可以把你有一个“免费咖啡 if 声明”放在第一个 if 中
  • 一般来说,将数据持久化到文件的优点是简单(只是读写一个新文件),数据库在效率、安全性和大数据集方面更好,虽然它们需要更多的理解并拥有自己的语言。我建议首先使用文件选项,以获取经验。
  • 所以我对这些东西很陌生。我该如何准确地做到这一点,这意味着我如何写入文件并让我的程序在每次再次运行时读取它??

标签: java loops memory continue


【解决方案1】:

如果您想确保保存进度,请尝试查看 RuntimeHook,如下所述:Intercepting java machine shutdown call?

您需要做的是将数据存储在文件中,即当前计数。这可以通过以下代码轻松完成:

public void saveToFile(int count)
{
    BufferedWriter bw = null;
    try
    {
        bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("countStorage"))));
        bw.write(count);
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
    finally
    {
        if(bw != null)
        {
            try
            {
                bw.close();
            }
            catch(IOException e) {}
        }
    }
}

public int readFromFile()
{
    BufferedReader br = null;
    try
    {
        br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("countStorage"))));
        String line = br.readLine();
        int count = Integer.parseInt(line);
        return count;
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
    finally
    {
        if(br != null)
        {
            try
            {
                br.close();
            }
            catch(IOException e) {}
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-22
    • 2017-01-20
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多