对两个整数的值进行互换(可以使用第三方变量):
class OperatorDemo{
public static void main(String[] args){
int a = 3 , b = 4;
int c;
c = a ;
a = b;
b = c;
}
}
}
对两个整数的值进行互换(不可以使用第三方变量)
class OperatorDemo{
public static void main(String[] args){
int a =3 , b = 4;
a = a ^ b;
b = a ^ b;
a = a ^ b;
}
}
三元运算符:
class Operator {
public void static main(String args[]){
int x = 3,y;
y = (x >1)?100:200;
System.out.println(y);
}
}
获取三个数中较大的数:
class Operator {
public void static main(String args[]){
int x = 1,y = 2, z = 4,temp,max;
temp = (x > y)?x:y;
max = temp > z ? temp : z;
}
}
if条件语句:
class IfDemo{
public void static main(String[] args){
int month = 9;
if(month <1 || month > 12)
System.out.println(month+"月没有对应的季节");
else if (month >= 3 && month <= 5)
System.out.println(month+"月对应春季");
else if (month >=6 && month <= 8)
System.out.println(month+"月对应夏季");
else if (month >= 9 && month <= 11)
System.out.println(month+"月对应秋季");
else
System.out.println(month+"月对应冬季");
}
}
数组:
找寻最值:
class ArrayDemo {
public void static main(String[] args){
int[] arr = {-11,22,44,93,532};
int max = getMax(arr);
System.out.println("数组的最大值是" + max);
}
public int static getMax(int[] arr){
int maxElement = 0;
if(int x = 0 ; x < arr.length ; x ++){
if(arr[x] > maxElement)
maxElement = arr[x];
}
return maxElement;
}
}
或者:
class ArrayDemo {
public void static main(String[] args){
int[] arr = {22,,23,25,56,76,435,345,34,234,15};
int maxIndex = getMaxIndex(arr);
System.out.println("数组的最大值是"+arr[maxIndex]);
}
public int static getMaxIndex(int[] arr){
int maxIndex = 0;
for(int x = 0 ; x < arr.length; x ++){
if(arr[x]> arr[maxIndex]){
maxIndex = x;
}
}
return maxIndex;
}
}