数组练习

  1.请编写一段英语单词学习程序,根据现实的星期,输入其英语表达。

* 使用随机数生成星期作为题目

* 学习者可以根据个人意愿循环操作

* 不连续出现同一个星期的题目

  如下所示:

请用小写输入英文的星期名。

星期三:wednesday

回答正确。再来一次?(yes/no):yes

星期一:monday

回答正确。再来一次? (yes/no):no

import java.util.Random;
import java.util.Scanner;

public class Test12 {
    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        Random r=new Random();
        int randomThis=-1;
        
        //将中文星期和英文星期分别保存两个数组内
        String[] cWeek= {"星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
        String[] eWeek= {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Sartday"};
        
        while(true) {
            int randomLast=randomThis;//把上一次获取的索引值储存
            randomThis=r.nextInt(7);//獲取隨機索引
            if(randomThis==randomLast) {
                continue;
            }
            System.out.println(cWeek[randomThis]);//輸出問題,中文星期
            String shuru=input.next();//獲取輸入
            //判断用户输入的答案和英文的星期是否匹配
            if(eWeek[randomThis].equals(shuru)) {
                System.out.println("回答正确");
            }
            else {
                System.out.println("回答错误");
            }
            
            System.out.println("再來一次?(yes/no):");
            String s=input.next();
            if(s.equals("No")) {
                break;
            }


        }
        
        
    }
    

2.请编写一段程序,创建一个元素类型为int型的数组,将1~10的随机数赋给数组的全部元素(赋入大于等于1小于等于10的数值)。元素个数通过键盘输入。并且元素的值都不相等。例如,不要出现{1,3,5,6,1,2}这样的情况(数组中的元素个数小于等于10)。

import java.util.Random;
//import java.util.Scanner;

//修改6-7中的程序,使得元素的值都不相等。例如,不要出现{1,3,5,6,1,2}这样的情况(数组中的元素个数小于等于10)。
public class Test09 {
    public static void main(String[] args) {
        int[] array = new int[10];
        Random r = new Random();
        for (int i = 0; i < 10; i++) {
            //獲取隨機數,範圍1到10
            int random = r.nextInt(10)+1;
            //調用方法exists,獲取返回值
            boolean exists = exists(array, random, i);
//如果返回值為true,不進行賦值,并且i--
            if (exists) {
                i--;
                continue;
                //返回值為false,賦值
            } else {
                array[i] = random;
            }
        }
      System.out.println(Arrays.toString(array));//打印数组
    }
//判斷生成的隨機數和index之前的元素是否相同,相同返回true,不相同返回false
    public static boolean exists(int[] a, int random, int index) {
        for (int i = 0; i < index; i++) {
            if (random == a[i]) {
                return true;
            }

        }
        return false;
    }
}

3.

 

posted @ 2020-03-24 20:54  kaolae  阅读(137)  评论(0)    收藏  举报