写的一个输入二进制,输出十进制的程序
void getInput() {
Scanner in = new Scanner(System.in);
System.out.print("Input a binary number: ");
int [color=red]inpNum[/color] = in.nextInt();
inpBin = String.valueOf(inpNum);
}
void testInput() {
if ([color=red]inpNum[/color] < NO3) { /* value must in the scope of int */
if ([color=red]inpNum[/color] < NO0) { /* value must bigger than 0 */
System.out.println("Input must be >=0" + "\n");
process();
} else if ([color=red]inpNum[/color] == NO0) { /* if value equals 0 */
System.out.println("0");
System.out.println("Base 2 Equals");
System.out.println("0");
System.out.println("Base 10");
} else {
for (int i=NO0; i<inpBin.length(); i++) {
if (inpBin.charAt(i) > '1') { /* value must be a binary */
System.out.println("Input must be a Binary number");
System.out.println();
process();
break;
} else if (i == inpBin.length()-NO1) {
System.out.print(inpBin);
System.out.println("\n" + "Base 2 Equals");
fact();
}
}
}
} else {
System.out.println("Input must be smaller than 2147483647");
}
}
⋯⋯⋯
⋯⋯⋯
private int inpNum; // value of input
private int baseNum; // used to obtain the value of decimal
private int mulNum; // used to shift when calculate
private String inpBin; // the String value of inpNum
在getInput()里将键盘输入的值赋给inpNum,并转化为String值给inpBin
但在testInput()里,inpNum就自动变成了0,inpBin的值还是刚刚赋予的值,这是为什么呢?
你搞错了
你这样int inpNum = in.nextInt(); 是在getInput方法定义一个局部变量
修改为inpNum = in.nextInt();
代码如下
[code="java"] void getInput() {
Scanner in = new Scanner(System.in);
System.out.print("Input a binary number: ");
[color=red]inpNum = in.nextInt(); [/color]
inpBin = String.valueOf(inpNum);
}
void testInput() {
if (inpNum < NO3) { /* value must in the scope of int /
if (inpNum < NO0) { / value must bigger than 0 /
System.out.println("Input must be >=0" + "\n");
process();
} else if (inpNum == NO0) { / if value equals 0 /
System.out.println("0");
System.out.println("Base 2 Equals");
System.out.println("0");
System.out.println("Base 10");
} else {
for (int i=NO0; i if (inpBin.charAt(i) > '1') { / value must be a binary */
System.out.println("Input must be a Binary number");
System.out.println();
process();
break;
} else if (i == inpBin.length()-NO1) {
System.out.print(inpBin);
System.out.println("\n" + "Base 2 Equals");
fact();
}
}
}
} else {
System.out.println("Input must be smaller than 2147483647");
}
}
⋯⋯⋯
⋯⋯⋯
private int inpNum; // value of input
private int baseNum; // used to obtain the value of decimal
private int mulNum; // used to shift when calculate
private String inpBin; // the String value of inpNum [/code]
String是对象,引用传递
int等基本类型按值传递。
[url]http://blog.csdn.net/faintbear/archive/2004/11/29/198021.aspx[/url]