作业2
设计一个用户类User,类中的变量有用户名、密码和记录用户数量的变量,定义3个构造方法:无参的、为用户名赋值的、为用户名和密码赋值的,还有获取和设置密码的方法和返回类信息的方法。
package Learn;
class User4 {
private String name ;
private String password;
private static int age ;
public User4(){
age++;
}
public User4(String name,String passward){
this.name=name;
this.password=passward;
age++;
}
//进行reture返回
public String getName(){
return name;
}
public void setName(String name){
}
public String getPassword(){
return password;
}
public void setPassword(String password){
}
public void sperk(){
System.out.println("用户名"+name+"密码"+password);
}
public void read(){
System.out.println("用户数目"+(age-1));
}
}
class z{
public static void main(String[] args) {
User4 m=new User4("刘","afc");
m.sperk();
User4 v=new User4("刘","afc");
v.sperk();
new User4().read();
}
}
设计一副牌Poker的外部类和一张牌Card的内部类。
(1)Poker类中定义私有成员花色数组、点数数组以及一副牌的数组属性,提供构造方法(创建并初始化一副牌的数组)、随机洗牌方法shuffle(Math.random()获取[0,1)的随机数;获取[n,m)的随机数公式为Math.random()*(m-n)+n)和发牌方法deal。
(2)Card类中定义花色和点数属性,提供打印信息方法。
(3)定义测试类并在main()方法中创建一副牌Poker对象,并调用shufle()进行洗牌,调用deal()进行发牌。
package Study;
class Poker {
//内部类Card
public class Card
{
private String suite; // 花色
private int face; // 点数
public Card(String suite, int face)
{
this.suite = suite;
this.face = face;
}
@Override
public String toString()
{
String faceStr = "";
switch (face)
{
case 1:
faceStr = "A";
break;
case 11:
faceStr = "J";
break;
case 12:
faceStr = "Q";
break;
case 13:
faceStr = "K";
break;
default:
faceStr = String.valueOf(face);
}
return suite + faceStr;
}
}
//Poker类 成员
private static String[] suites = { "黑桃", "红桃", "梅花", "方块" };
private static int[] faces = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 };
private Card[] cards;
//构造器
public Poker()
{
//构造52个Card对象 存放在cards 数组中
cards = new Card[52];
for (int i = 0; i < suites.length; i++)
{
for (int j = 0; j < faces.length; j++)
{
cards[i * 13 + j] = new Card(suites[i], faces[j]);
}
}
}
//洗牌 (随机乱序)
public void shuffle()
{
int len = cards.length;
for (int i = 0; i < len; i++)
{
int index = (int) (Math.random() * len);
Card temp = cards[index];
cards[index] = cards[i];
cards[i] = temp;
}
}
//获取一个Card 对象
public Card getCard(int index)
{
return cards[index];
}
}
class Test
{
public static void main(String[] args)
{
Poker poker = new Poker();
poker.shuffle(); // 洗牌
Poker.Card c1 = poker.getCard(0); // 发第一张牌
// 对于非静态内部类Card
// 只有通过其外部类Poker对象才能创建Card对象
Poker.Card c2 = poker.new Card("红心", 1); // 自己创建一张牌
System.out.println(c1); // 洗牌后的第一张
System.out.println(c2); // 打印: 红心A
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?