资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

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://www.cdkjz.cn/article/dddgoj.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220