Java 中的余数运算符
本文将介绍 Java 中的余数运算符及其用途。
在 Java 中使用余数运算符计算整数除法的余数
在 Java 中,模或余数运算符由符号 %
给出。它计算一个数字除以另一个数字的余数。
假设我们有两个值:value1 = 20
,value 2 = 35
。这里,value1
是被除数,value2
是除数。
例子:
// load package
package JavaPercentagesymbol;
import java.util.Scanner;
// main class starts here
public class SymbolExample {
// main function
public static void main(String[] args) {
// value1/value2%remainder
int value1, value2, remainder;
value1 = 20;
value2 = 35;
System.out.println("value1=20; value2=35");
remainder = value1 % value2;
System.out.println("The remainder is: " + remainder);
}
// primary function ends here
}
// main class ends here
输出:
value1=20; value2=35
The remainder is: 20
在 Java 中使用提醒运算符获取字符串长度
在下面的代码块中,String[] username
的长度是 4,而 int length
的大小会有所不同。但是,模运算符正确地确定了实际长度。
由于用户名的长度为四,余数运算符将其除以字符串的长度,而不是可变整数长度的长度。
例子:
package JavaPercentagesymbol;
public class SymbolExample {
public static void main(String[] args) {
String[] username = {"John", "Smith", "Martin", "Herry"};
int length;
length = 6 % username.length;
System.out.println("modulo 1: " + 6 % 4);
System.out.println(" 6 % 4 is " + length + ": " + username[length]);
length = 7 % username.length;
System.out.println("modulo 2: " + 30 % 4);
System.out.println(" 70 % 4 is " + length + ": " + username[length]);
length = 40 % username.length;
System.out.println("modulo 3: " + 40 % 4);
System.out.println("60 % 4 is " + length + ": " + username[length]);
length = 49 % username.length;
System.out.println("modulo 4: " + 49 % 4);
System.out.println("60 % 4 is " + length + ": " + username[length]);
}
}
输出:
modulo 1: 2
6 % 4 is 2: Martin
modulo 2: 2
70 % 4 is 3: Herry
modulo 3: 0
60 % 4 is 0: John
modulo 4: 1
60 % 4 is 1: Smith
取模 %
确定 String[]username
的实际长度来自 username.length
数组索引。
但如你所见,int length
的长度是 7、40 和 49。
这就是程序如何智能地返回 username.length
的剩余部分,而不是给我们剩余的无序 int length
值。
在 Java 中使用余数运算符检查偶数/奇数
下面的程序是一个入门级的 Java 逻辑构建器。它确定(整数)中的给定输入是偶数还是奇数。
例子:
package JavaPercentagesymbol;
import java.util.Scanner;
public class SymbolExample {
public static void main(String[] args) {
int value;
try (Scanner in = new Scanner(System.in)) {
System.out.println("Please, ender a number to check if it is even or odd?");
value = in.nextInt();
}
// determine the even value%2==0 will always be even
if ((value % 2) == 0) {
System.out.println(+value + " is EVEN ");
// else, it is definitely going to be odd
} else {
System.out.println(+value + " is ODD");
}
}
}
输出:
Scanner 使用上面代码中作为参数传递的输入流生成一个新的 Scanner 对象。
nextInt()
方法采用一串数字并将其更改为 int
数据类型。它从 Scanner 获得相同的传递参数。
Sarwan Soomro is a freelance software engineer and an expert technical writer who loves writing and coding. He has 5 years of web development and 3 years of professional writing experience, and an MSs in computer science. In addition, he has numerous professional qualifications in the cloud, database, desktop, and online technologies. And has developed multi-technology programming guides for beginners and published many tech articles.
LinkedIn