Java按位与与==和+的优先级比较-创新互联

文章目录
    • &与==
      • 1.代码篇
      • 2.报错提醒
      • 3.改错方式
    • 2.&与=

目前创新互联已为上1000+的企业提供了网站建设、域名、网站空间网站托管、企业网站设计、渌口网站维护等服务,公司将坚持客户导向、应用为本的策略,正道将秉承"和谐、参与、激情"的文化,与客户和合作伙伴齐心协力一起成长,共同发展。&与== 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.报错提醒

1
原因是编译器先进行b==1的返回值计算在进行按位与。

3.改错方式
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://csdahua.cn/article/dddgoj.html
扫二维码与项目经理沟通

我们在微信上24小时期待你的声音

解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流