2013年12月1日星期日

Novice help java problem ,

/ * Title:
1 * write a program to achieve the following functions:
randomly assigned an integer between a 1 ~ 100 (Math.random () Returns the number of a double class ) ;
users to enter their guess from the keyboard
program returns tips , tips are " big guess ," " Guess small " and " guessed right ."
The user can enter information as prompted speculation again until the message is " guessed ."
* /



import java.util *.;

public class RandomTest {
public static void main (String [] args) throws Exception {
byte [] b = new byte [1024];
System.out.println ("- Enter a number from 0 to 100 : - " ) ;
System.in.read (b);
String str = new String (b) trim ().;
double num = Double.parseDouble (str);
double ran = (Math.random () * 100) +1;
while (num> ran) {
System.out.println (" big, please re- enter:" ) ;
Scanner in = new Scanner (System.in);
num = in.nextDouble ();
if (num == ran) {
System.out.println (" got it " ) ;
break;
}
}
while (num System.out.println (" small, please re- enter:" ) ;
Scanner in = new Scanner (System.in);
num = in.nextDouble ();
if (num == ran) {
System.out.println (" got it " ) ;
break;
}
}
System.out.println (" Yes ! " ) ;
}
}

figure out how to be wrong, is that the original signature can also CMD , the sudden knock big , and actually got it . . . In every case . .
------ Solution ---------------------------------------- ----
code written in question, after the smaller will no longer big, go directly to the right , look at the code

while(num<ran){
    System.out.println("小了,请重新输入:");
    Scanner in=new Scanner(System.in);
    num= in.nextDouble();
    if(num==ran){     // 如果此时num > ran,则跳出循环,顺势向下走到"对了"了
        System.out.println("答对了");
        break;
    }
}
System.out.println("对了!");

------ Solution ------------------------------------- -------
public static void main (String [] args) throws Exception {
System.out.println ("- Enter a number from 0 to 100 : - " ) ;
Scanner in = new Scanner (System.in);
int num = in.nextInt ();
int ran = (int) (Math.random () * 100) + 1;
while (true) {
if (num> ran) {
System.out.println (" big, please re- enter:" ) ;
num = in.nextInt ();
} else if (num System.out.println (" small, please re- enter:" ) ;
num = in.nextInt ();
} else {
System.out.println (" got it " ) ;
break;
}
}
------ For reference only --------------------------------- ------
public static void main(String[] args) throws Exception {
System.out.println("-请输入0到100的一个数:-");
Scanner in = new Scanner(System.in);
int num = in.nextInt();
int ran = (int) (Math.random() * 100) + 1;
while (true) {
if(num > ran) {
System.out.println("大了,请重新输入:");
num = in.nextInt();
} else if(num < ran) {
System.out.println("小了,请重新输入:");
num = in.nextInt();
} else {
System.out.println("答对了");
break;
}
}

没有评论:

发表评论