Steven_Tian
unread,Nov 19, 2010, 6:17:39 PM11/19/10Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to Good Ideas
import java.util.Scanner; // program use class Scanner
public class B9916025_hw05 // main method begins execution of Java
application
{
public static void main(String args[]) {
Scanner input = new Scanner(System.in); // create Scanner to obtain
String two = ""; // input from command window
do {
System.out.printf("\nPlease enter a binary integer : ");
two = input.next();
if (two.length() > 10) {
System.out
.printf("\nSorry!! This program can only calculate to the decade
1023.\n"
+ "That is you only can enter ten digits in the binary number.\n");
}else if (isBin(two)) {
System.out
.printf("\nThe integer that you entered is not a binary integer.
\n");
} else {
int ten = 0;
int binary = Integer.parseInt(two);
for (int i = 1; i <= two.length(); i++) {
if ((binary % Math.pow(10, i)) / Math.pow(10, i - 1) == 1) {
ten += Math.pow(2, i - 1);
binary = binary - binary % (int) (Math.pow(10, i));
} // end if
else if ((binary % Math.pow(10, i)) / Math.pow(10, i - 1) == 0)
continue;
} // end for
System.out.printf("\nThe decimal number is %d\n", ten);
} // end else
} while (two.length() > 10 || isBin(two));
} // end method main
public static boolean isBin(String str){
boolean r=false;
for(int i=0;i<str.length();i++){
char c=str.charAt(i);
if( c > '1' || c< '0'){
r=true;
break;
}
}
return r;
}
} // end class B9916025_hw06