Calculator exercises
Basic grammar exercises:
//自己做的简陋低端计算器^-^
import java.util.Scanner;
public class A0121Calculator {
public static void main(String[] args) {
Scanner num= new Scanner(System.in);
double b=0;
double e=0;
while (num.hasNextDouble()){
b=num.nextDouble();}
String c="1";
if (num.hasNext()){
c=num.next();}else{
return;}
switch (c){
case"+":if (num.hasNext()){
e=num.nextDouble();
System.out.println(b+e);return;}else{
return;}
}
switch (c){
case"-":if (num.hasNext()){
e=num.nextDouble();
System.out.println(b-e);return;}else{
return;}
}
switch (c){
case"*":if (num.hasNext()){
e=num.nextDouble();
System.out.println(b*e);return;}else{
return;}
} switch (c){
case"/":if (num.hasNext()){
e=num.nextDouble();
System.out.println(b/e);return;}else{
return;}
}
num.close();
}
}
Array
Array definition
- An array is an ordered collection of data of the same type
- The array describes several data of the same type, arranged and combined in a certain order
- Among them, each array is called an array element, and each array element can be accessed through a subscript
Array declaration creation
The array variable must be declared before the array can be used in the program. The following is the syntax for declaring array variables:
dataType[] arrayRefVar; //首选的方法
dataType arrayRefVar[]; //效果相同,但不是首选方法
The Java language uses the new operator to create an array, the syntax is as follows:
dataTypep[] arrayRefVar = new dataType[arraySize];
Array elements are accessed by index, array index starts from 0
Get the length of the array: array.length
public class A0121Array {
public static void main(String[] args) {
// 变量的类型 变量的名字 = 变量的值;
int[] numbers; //1.声明一个数组
numbers=new int[5]; //2.创建一个数组
//也可以直接这样写: int[] numbers = new int[5];
numbers[0]=1;
numbers[1]=2;
numbers[2]=3;
numbers[3]=4;
numbers[4]=5;//3.给数组元素中赋值
//计算数组的和
int a=0;
//获取数组长度:array.length
for (int i = 0; i < numbers.length; i++)
{
a=numbers[i]+a;
}
System.out.println(a);
}
}