Java按位与与==和+的优先级比较-创新互联
文章目录
网站名称:Java按位与与==和+的优先级比较-创新互联
文章地址:http://scyanting.com/article/dddgoj.html
- &与==
- 1.代码篇
- 2.报错提醒
- 3.改错方式
- 2.&与=
import java.util.Scanner;
public class NumberOne {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);
System.out.print("Please enter a number >");
while (scanner.hasNextInt()) { int a = scanner.nextInt();
System.out.println(countOne(a));
System.out.print("Please enter a number >");
}
}
public static int countOne (int number) {int b = 1, counter = 0;
while (number != 0) { if (number & b == 1){
counter++;
}
number = number >>>1;
}
return counter;
}
}
2.报错提醒
原因是编译器先进行b==1的返回值计算在进行按位与。
import java.util.Scanner;
public class NumberOne {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);
System.out.print("Please enter a number >");
while (scanner.hasNextInt()) { int a = scanner.nextInt();
System.out.println(countOne(a));
System.out.print("Please enter a number >");
}
}
public static int countOne (int number) {int b = 1, counter = 0;
while (number != 0) { if ((number & b) == 1){
counter++;
}
number = number >>>1;
}
return counter;
}
}
加上括号就可以啦!
2.&与=import java.util.Scanner;
public class OddEvenBitBinary {public static void main(String[] args) { Scanner sc = new Scanner(System.in);
System.out.print("Please enter an integer >");
while(sc.hasNextInt()) { int number = sc.nextInt();
oddEven(number);
System.out.println();
System.out.print("Please enter an integer >");
}
}
public static void oddEven(int num) {System.out.print("The odd bit of " + num + ">");
int j = 1;
int i = 0;
for (i = 30; i >= 0; i = i - 2) { System.out.print(" " + ((num >>i) & j));
}
System.out.println();
System.out.print("The even bit of " + num + ">");
for (i = 29; i >= 1; i -= 2) { System.out.print(" " + ((num >>i) & j));
}
}
}
System.out.print(" " + ((num >>i) & j)); 这一行代码的括号必须全加上,不然会出现报错!
你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧
网站名称:Java按位与与==和+的优先级比较-创新互联
文章地址:http://scyanting.com/article/dddgoj.html