当前位置: 首页 > 知识库问答 >
问题:

我开始了我的Java编码经验,我试图用数组和方法编写一个杂货店结帐程序

秦琦
2023-03-14
    //Initializing scanner declaring arrays
    Scanner scan= new Scanner (System.in); 
    int quantity[]=new int[3];
    String name[]=new String[3];
    double price[]=new double [3];

    //do while loop to continue entering items until quantity is 0
    do
    {

        System.out.println("Enter quantity of item, " + "name of item, " + " and price of item, " );
        quantity[i]= scan.nextInt();
        name[i]=scan.next();
        price[i]=scan.nextDouble();
        i++;
    }while(quantity[i]==0);


    //menu for grocery list operations using switch block
    System.out.println("1) Add item(s)/n"
            + "2) Remove item(s)/n"
            + "3) view cart/n "
            + "4) Checkout/n "
            + "5) Exit/n");
    ch=scan.nextInt();
    switch(ch) 
    {
    case 1: 


        add(quantity[i-1],name[i-1],price[i-1]);
        break;

下面是方法add

//method to add item
public static  void add(int q,String  n,double p )

{
    Scanner scan= new Scanner (System.in);
    System.out.println("Enter quantity of item, " + "name of item, " + " and price of item, " );
    q=scan.nextInt();
    n= scan.next();
    p=scan.nextDouble(); 
    scan.close();


}

共有1个答案

邵华皓
2023-03-14

在java中,将数组作为参数传递和返回数组非常简单。

下面是一个例子:

public static int[] foo(int[] a){
    // Do something with a
    int[] b = {0,1,2};
    return b;
}

但也要记住,Java是按值传递的,但是当您将数组作为参数传递时,它将引用(也称为内存地址)作为值传递给函数。

public static void main(String... args){
    int b = 5;
    foo1(b);
    // b is still 5


    int[] c = {1,2};
    foo2(c);
    // c is now {1,10} 
}

public static void foo1(int x){
    x = 10;
}

public static void foo2(int[] x){
    x[1] = 10;
}
 类似资料:
  • 有许多有限状态机提出的问题,但都与我的问题无关。 我需要5种方法 我们从里面开始 我们想打印状态→ 0和输出0→ 读取输入首先在ebx中,第二个将在eax中 做完整的程序 这是我的代码:这里的问题是输入不起作用。如果我输入00,01,11-

  • 问题内容: 我刚刚在Windows Vista上安装了JDK。之后,我为4个环境变量设置了适当的值:classpath,include,lib,path。之后,我可以编译我的HelloWorld程序(我得到了* .class文件)。但是,当我尝试执行已编译的程序(我键入java HelloWorldApp)时,它不起作用。Java写了很多东西,最后写成“找不到主类:HelloWorldApp”。请

  • 我在flutter中编写了一个注册屏幕,我使用了Firebase,但我却遇到了这个错误,但在我的项目中,我在Android\App中有google-services.json。我不明白你为什么能帮我?我做了初始化和Firebase网站的东西 E/flutter(26694):[错误:flutter/lib/ui/ui_dart_state.cc(166)]未处理得异常:[core/not-init

  • 下面是我的代码: 如果有人能给我一些想法,我将不胜感激:)

  • 我正试图将editbook功能添加到我的java bookstore asignment中,但我无法让它工作。我很确定我很接近,只是逻辑不太正确 以下是我收到的一些错误代码: org.springframework.beans.factory.不满意依赖异常:创建名为bookstore Controller的bean时出错:通过字段存储库表示不满意的依赖关系; 原因:org。springframe

  • 我的项目的整个依赖关系如下代码所示: 我想用来计算两个格式为'yyyy-mm-ss hh:mm:ss.ss'的输入日期字符串之间的时间间隔(例如'2017-12-26 00:00:02.044'),结果将加倍,精度达到毫秒,例如,当我传递“2017-12-26 00:00:02.044”、“2017-12-26 00:00:03.045”给时,结果将是1.001秒,然后附带Java代码段: 使用的