10、数组示例
数组示例
1、猜数游戏:从键盘中任意输入一个数据,判断数列中是否包含此数。
2、打印正三角形
多维数组示例:
1、一起来参加屌丝程序员大赛吧,有3个班各3名程序员参赛,记录每个学员的成绩,并计算每个班的平均分。
解示例1:
import java.util.Scanner;
public class a
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int[] nums = {3, 21,42,36,19};
System.out.print("猜猜我这边的数字(0~50整数):");
int usernum = input.nextInt();
boolean bool = false;
for(int x:nums)
{
if(usernum == x)
{
bool = true;
}
}
if(bool == true)
System.out.println("猜对了!");
else
System.out.println("猜错了");
}
}
//分支、循环语句,如果后面只有一句话就能结束,可以不加{}。就像第18~21行一样。其实11~17行那两个大括号都可以省略。
当然,nums里面是我本身定义的数字,如果想让电脑生成随机数,则有:
import java.util.Scanner;
import java.util.Random;//引入随机数工具
public class a
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int[] nums = new int[5];
int len = nums.length;
Random r = new Random();//创建一个可以生成随机数的工具
for(int i = 0 ; i < len ; i++)
nums[i] = r.nextInt(50);
System.out.print("猜猜我这边的数字(0~50整数):");
int usernum = input.nextInt();
boolean bool = false;
for(int x:nums)
{
if(usernum == x)
{
bool = true;
}
}
if(bool == true)
System.out.println("猜对了!");
else
System.out.println("猜错了");
}
}
解示例2:
public class a
{
public static void main(String[] args)
{
char[] array = {'A','B','C','D','E','F','G'};
int len = array.length;
for(int i = 1;i <= len; i++)
{
for(int j = i;j < len; j++)
{
System.out.print(" ");
}
for(int j = 1;j <= 2*i-1;j++)
{
System.out.print(array[i-1]);
}
System.out.println();
}
}
}