今天使用static 修饰的变量时:
package com.day7.demo4;
public class Pengue {
String name;
String sex;
int love=0;//亲密度
int health=60;//健康值
static final String SEX_MALE = "Q仔";
static final String SEX_FEMALE = "Q妹";
public Pengue() {
super();
}
public Pengue(String name, String sex, int love, int health) {
super();
this.name = name;
this.sex = sex;
this.love = love;
this.health = health;
}
/**
* 打印信息
*/
public void print() {
System.out.println("姓名:"+name+",性别:"+sex+",和主人亲密度:"+love+",健康值:"+health);
}
}
在PengueTest.java中使用时如下:
System.out.print("请选择企鹅的性别:(1.Q仔 2.Q妹)");
int num = sc.nextInt();
if (num == 1) {
Pengue.SEX_MALE;
}else if (num ==2) {
Pengue.SEX_FEMALE;
}
报错如下:
Syntax error, insert "VariableDeclarators" to complete LocalVariableDeclaration
修改如下后就正确了:
System.out.print("请选择企鹅的性别:(1.Q仔 2.Q妹)");
int num = sc.nextInt();
if (num == 1) {
pengue.sex = Pengue.SEX_MALE;
}else if (num ==2) {
pengue.sex = Pengue.SEX_FEMALE;
}
即将其赋值给一个变量,因为这种情况就相当于 1;因为SEX_MALE现在是常量,以后要避免这种错误;