java初学者题目,求详细解答

猜数字游戏:一个类A有一个成员变量v,有一个初值100。定义一个类,对A类的成员变量v进行猜。如果大了则提示大了,小了则提示小了。等于则提示猜测成功。

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Random;
public class TestNumber {
private A a;
public void setA(A a) {
this.a = a;
}
public A getA() {
return a;
}
public boolean judge(int num) {
if (a.getV() > num) {
System.out.println("小了");
return false;
}
if (a.getV() < num) {
System.out.println("大了");
return false;
} else {
System.out.println("猜对了");
return true;
}
}
public static void main(String[] args) {
TestNumber t = new TestNumber();
A a = new A(new Random().nextInt(100));
t.setA(a);
BufferedReader str = new BufferedReader(
new InputStreamReader(System.in));
while (true) {
System.out.println("请输入要猜的数:");
try {
if (t.judge(Integer.parseInt(str.readLine()))) {
break;
}
} catch (Exception e) {
System.out.println("输入错误请重新输入:");
}
}
}
}
class A {
private int v = 100;
public A(int v) {
this.setV(v);
}
public A() {
}
public void setV(int v) {
this.v = v;
}
public int getV() {
return v;
}
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-04-11
以下是标准答案:

import javax.swing.JOptionPane;
public class Text {
public static void main(String[] args) {
int number=(int)(Math.random()*100);
String num;
num=JOptionPane.showInputDialog(null," 请猜计算机输出的数:(0~100)");
int i=Integer.parseInt(num);
while(i!=number)
{
if(i>number)
JOptionPane.showMessageDialog(null,"输入的数值大了");
else
{
JOptionPane.showMessageDialog(null,"输入的数值小了");
}
num=JOptionPane.showInputDialog(null," 请猜计算机输出的数:(0~100)");
i = Integer.parseInt(num);
}
System.out.println("恭喜你猜对了!");
}
}本回答被提问者和网友采纳
第2个回答  推荐于2018-05-06
在B.java 的文件中:
A{
public int v = 100;
}
public B{

public static void main(String[] args){
int temp = new A().v;
Scanner scan = new Scanner(system.in);
while(true){
int v = scan.nextInt();
if(v>temp){
System.ou.println("输入值大了");
continue;
}else if(v<temp){
System.ou.println("输入值小了");
continue;
}else{
System.ou.println("你猜对了!NB!");
break;
}
}
}

}

导包自己导下就OK;欢迎追问。