我正在尝试编写一个简单的程序,它有2个类,一个用set方法,另一个用main,可执行方法。
头等舱:
import java.util.ArrayList;
public class Practice
{
private String firstName;
private String lastName;
ArrayList<Double> sales = new ArrayList<Double>();
public Practice(String firstName, String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getFirstName()
{
return firstName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
public String getLastName()
{
return lastName;
}
public void addSales(double sale)
{
sales.add(sale);
}
public ArrayList<Double> returnSales()
{
return sales;
}
}
主类:
import java.util.Scanner;
public class PracticeExecutable {
public static void main(String[] args)
{
double sale;
String firstName;
String lastName;
Scanner input = new Scanner(System.in);
System.out.println("Please Enter first name: ");
firstName = input.nextLine();
System.out.println("Please Enter last name: ");
lastName = input.nextLine();
Practice employee = new Practice(firstName, lastName);
do
{
System.out.println("Please enter sale amount or -1 to quit: ");
sale = input.nextDouble();
if(sale == -1)
break;
}while(sale != -1);
employee.addSales(sale);
input.close();
System.out.println("Name: " + employee.getFirstName() + " " +
employee.getLastName());
System.out.println("Sales: " + employee.returnSales());
}
}
我正在尝试将用户输入传递到ArrayList销售中,然后打印输入的销售,但似乎只是识别&#39; -1&#39;作为销售。我似乎无法找到问题。
答案 0 :(得分:1)
这是因为在循环中您只检查销售是否无效并且对有效销售价值不做任何操作。当您退出循环(销售输入为-1)时,您将错误的值添加到列表中。为了改变这个简单的移动employe.addSales(sale)就像这样循环:
do {
System.out.println("Please enter sale amount or -1 to quit: ");
sale = input.nextDouble();
if(sale == -1) break;
employee.addSales(sale);
} while(sale != -1);
答案 1 :(得分:1)
仔细观察这一行:
employee.addSales(销售);
这是将销售额添加到ArrayList的行。该行只运行一次,它的值始终为-1。当销售为-1时,循环中断时的结果。所以它只是将-1添加到ArrayList,没有别的 您需要做的是在do while block中移动此行。当sales的值不等于-1时,确保将销售添加到ArrayList。休息会很好。