1.
public class Account
{
private String name;
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
}
import java.util.Scanner;
public class AccountTest
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Account myAccount = new Account();
System.out.printf(“Initial name is: %s%n%n”, myAccount.getName());
System.out.println(“Please enter the name:”);
String theName = input.nextLine();
myAccount.setName(theName);
System.out.println();
System.out.printf(“Name in object myAccount is:%n%s%n”, myAccount.getName());
}
}
2.
public class Account2
{
private String name;
public Account2(String name)
{
this.name = name;
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
}
public class AccountTest2
{
public static void main(String[] args)
{
Account2 account1 = new Account2(“David Lee”);
Account2 account2 = new Account2(“Paul Lee”);
System.out.printf(“account1 name is: %s%n”, account1.getName());
System.out.printf(“account2 name is: %s%n”, account2.getName());
}
}
3.
public class Account3
{
private String name;
private double balance;
public Account3(String name, double balance)
{
this.name = name;
if (balance > 0.0)
{
this.balance = balance;
}
}
public void deposit(double depositAmount)
{
if (depositAmount > 0.0)
{
balance = balance + depositAmount;
}
}
public double getBalance()
{
return balance;
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
}
import java.util.Scanner;
public class AccountTest3
{
public static void main(String[] args)
{
Account3 account1 = new Account3(“David Lee”, 50.00);
Account3 account2 = new Account3(“Paul Lee”, 10.00);
System.out.printf(“%s balance:
System.out.printf(“
S
y
s
t
e
m
.
o
u
t
.
p
r
i
n
t
f
(
“
%.2f%n%n”, account2.getName(), account2.getBalance());
Scanner input = new Scanner(System.in);
System.out.print(“输入帐户1的存款金额(Enter deposit amount for account1): “);
double depositAmount = input.nextDouble();
System.out.printf(“%nadding %.2f to account1 balance%n%n”, depositAmount);
account1.deposit(depositAmount);
System.out.printf(“%s balance:
System.out.printf(“
S
y
s
t
e
m
.
o
u
t
.
p
r
i
n
t
f
(
“
%.2f%n%n”, account2.getName(), account2.getBalance());
System.out.print("输入帐户2的存款金额(Enter deposit amount for account2): ");
depositAmount = input.nextDouble();
System.out.printf("%nadding %.2f to account2 balance%n%n", depositAmount);
account2.deposit(depositAmount);
System.out.printf("%s balance: $%.2f%n", account1.getName(), account1.getBalance());
System.out.printf("%s balance: $%.2f%n%n", account2.getName(), account2.getBalance());
}
}
4.
import javax.swing.JOptionPane;
public class NameDialog
{
public static void main(String[] args)
{
String name = JOptionPane.showInputDialog(“what’s your name?”);
String message = String.format(“Welcome, %s, to Java Programming!”, name);
JOptionPane.showMessageDialog(null, message);
}
}