水仙花数
import java.util.*; //万能头
public class Main
{
public static void main(String[] args)
{
for(int i=100;i<1000;i++)
{
if(isYes(i))
{
System.out.println(i);
}
}
}
public static boolean isYes(int x)
{
int a=x/100,b=x/10%10,c=x%10;
if(x==a*a*a+b*b*b+c*c*c) return true;
else return false;
}
}
练习题:面向对象 封装百分制分数
需求:封装百分制分数,和它对应的五档分制分数
分数类
public class Score {
int score;
char level;
public Score(int score) {
this.score = score;
this.level = setLevel(score);
}
private char setLevel(int s) {
char r = 0;
switch(s/10)
{
case 10: case 9:
r = 'A';
break;
case 8:case 7:
r = 'B';
break;
case 6:
r = 'C';
break;
case 5:case 4:case 3:case 2:
r = 'D';
break;
case 1:case 0:
r = 'E';
break;
}
return r;
}
public String toString() {
return score+", "+level;
}
}
主函数
public class zhuhanshu
{
public static void main(String[] args)
{
Score s = new Score(20);
System.out.println(s.toString());
}
}
练习题:面向对象 打印图形
需求:设计一个可以随机打印形状的代码
主函数
import java.util.*; //万能头
public class zhuhanshu
{
public static void main(String[] args)
{
System.out.println("按回车继续");
while(true) {
int r = new Random().nextInt(4);
switch(r)
{
case 0: f(new Shape()); break;
case 1: f(new Line()); break;
case 2: f(new Square()); break;
case 3: f(new Circle()); break;
}
}
}
static void f(Shape s) {
System.out.println("----------------");
new Scanner(System.in).nextLine();
s.draw();
if(s instanceof Line)
{
Line line = (Line) s;
line.length();
}
new Scanner(System.in).nextLine();
s.clear();
}
}
父类
public class Shape {
public void draw()
{
System.out.println("图形形状");
}
public void clear()
{
System.out.println("\n\n\n");
}
}
直线类
public class Line extends Shape {
public void draw() {
System.out.println("打印一条直线 ————");
}
public void length() {
System.out.println("一米多。。。");
}
}
圆形类
public class Circle extends Shape{
public void draw()
{
System.out.println("打印一个圆形 o");
}
}
方形类
public class Square extends Shape {
public void draw()
{
System.out.println("打印一个方形 口");
}
}
标签:case,Java,void,System,public,println,习题,12.9,out
From: https://www.cnblogs.com/Vivian-0918/p/16968915.html