空指针异常在调用getter函数时发生。请尽快提供帮助。我最后写了错误。我还提到了发生错误的那一行。不过,部分输出是正确的。
import java.util.Scanner;
public class Solution
{
public static void main(String args[] ) throws Exception
{
/* Do not alter code in main method */
Shirt[] shirts = new Shirt[5];
Scanner sc = new Scanner(System.in);
for(int i = 0;i<5;i++)
{
int tag = sc.nextInt();sc.nextLine();
String brand = sc.nextLine();
double price = sc.nextDouble();sc.nextLine();
char g = sc.nextLine().charAt(0);
shirts[i] = new Shirt(tag,brand,price,g);
}
double price = sc.nextDouble();
for(Shirt s: shirts)
{
System.out.println(getDiscountPrice(s));
}
Shirt[] result = getShirtWithMoreThanSpecificPrice(shirts,price);
for(Shirt s: result)
{
System.out.println(s.getTag()+" "+s.getPrice()+" "+s.getBrand());//This is where the exception occurs
}
}
public static double getDiscountPrice(Shirt s)
{
double p;
if(s.g=='m')
{
p=s.price-((0.1*s.price));
return p;
}
if(s.g=='f')
{
p=s.price-((0.2*s.price));
return p;
}
if(s.g=='u')
{
p=s.price-((0.3*s.price));
return p;
}
return 0.0;
}
public static Shirt[] getShirtWithMoreThanSpecificPrice(Shirt[] shirts,double price)
{
Shirt[] sh=new Shirt[5];
for(int i=0;i<5;i++)
{
if(shirts[i].price>price)
{
sh[i]=shirts[i];
}
}
return sh;
}
}
class Shirt
{
//define the class as per details shared in the question
int tag;
String brand;
double price;
char g;
public Shirt(int tag,String brand,double price,char g)
{
this.brand=brand;
this.g=g;
this.price=price;
this.tag=tag;
}
public void setG(char g)
{
this.g = g;
}
public void setTag(int tag)
{
this.tag = tag;
}
public void setBrand(String brand)
{
this.brand = brand;
}
public void setPrice(double price)
{
this.price = price;
}
public int getTag()
{
return tag;
}
public double getPrice()
{
return price;
}
public String getBrand()
{
return brand;
}
public char getG()
{
return g;
}
}
错误:
线程“ main”中的异常java.lang.NullPointerException在 Solution.main(Solution.java:32
第32行出现错误。我试图初始化变量。没有一个是成功的。