如果可能,将多个值存储在变量中

时间:2013-11-17 19:07:20

标签: java while-loop do-while

想知道是否有人可以帮助我,我正在尝试创建一个程序,累计为每本书输入的所有价格的总额,只要do / while循环保持循环,但我只有这样远远是每次循环重启时它会删除先前分配的变量值!任何人都可以引导我朝着正确的方向前进吗?我刚开始使用java,所以我的知识库非常低。

String surname, firstname, email, cfn, btitle, finished;
double pno, nochild, cage, noboks, costbook=0, totalcost, averagecost, price;




            k = new Scanner(System.in);
             System.out.print("Welcome - What is your Family surname?");
              surname = k.next();
             System.out.print("What is your own first name?");
             firstname=k.next();
             System.out.print("What is your email address?");
              email=k.next();
              System.out.print("What is your phone number?");
             pno=k.nextInt();
             System.out.print("How many children do you have?");
             nochild=k.nextInt();
             System.out.print("You are Alan " + surname);
              System.out.println();





             int childcounter=1;
            do{
              System.out.print("What is your childs first name "+childcounter+" of " +nochild+"?");
              cfn=k.next();
              System.out.print("What is "+cfn+"'s age?");
              cage=k.nextInt();
              System.out.println();
              do {
              System.out.print("What is the title of the book "+cfn+" would like?");
              btitle=k.next();      
              System.out.print("Price of '"+btitle+"' ?");
             price=k.nextDouble();
              System.out.println();


              System.out.print("Do you want to finish? y/n ");
              finished=k.next();





              }
             while (finished.equalsIgnoreCase("n"));


            if (finished.equalsIgnoreCase("y"))
            {

            }
              childcounter++;
            }
        while (childcounter <= nochild);
            System.out.print("Heres the book price €"+price);
            }

3 个答案:

答案 0 :(得分:0)

像这样使用

String[][] data = new String[numberOfLoops][numberOfVariable];

所以你可以使用

data[nthIteration][variable] = scanner.next();

答案 1 :(得分:0)

要让变量在循环中持续存在,您需要在循环开始之前定义它们。如果在循环内部定义了变量,则在循环结束后将删除该变量。

    int test;
    for (int i=0; i < 10; i++)
    {
        test = test * i;
    }
    //test's value will persist 

教程:Java >> Variable Scope


如果要将多个值存储到变量中,则应该查看Arrays

教程:Java >> Arrays

答案 2 :(得分:0)

您可能需要定义一个包含这些变量/字段的类:

public class MyInfo {
  String surname, firstname, email, cfn, btitle, finished;
  double pno, nochild, cage, noboks, costbook=0, totalcost, averagecost, price;
}

然后在while循环的每次迭代中创建类的新实例,并将每个新对象存储在list / ArrayList中