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