日撸java三百行 day2

本文介绍了Java编程中的while语句实现,探讨了两种循环结构,并通过实例演示如何处理综合任务,如计算成绩总分、查找最大值和最小值。同时讲解了顺序列表的创建和操作,包括构造方法和toString方法的使用。
摘要由CSDN通过智能技术生成

目录

1、while语句

2、综合任务 

3、顺序表(一)


1、while语句

这里主要讲了两种方式来进行循环判断,第一种是在while中执行条件来作为判断,如果满足条件则继续执行,不满足的退出循环。第二种是在循环内部通过判断语句来判断是否满足条件,如果满足条件则通过break来

package basic;

/**
 * @author Fan Min minfanphd@163.com.
 **/
public class WhileStatement {
    /**
     * The entrance of the program.
     *
     * @param args Not used now.
     */
    public static void main(String args[]){
        whileStatementTest();
    }//of main
    /**
     * The sum not exceeding a given value.
     */
    public static void whileStatementTest(){
        int tempMax = 100;
        int tempValue = 0;
        int tempSum = 0;

        //Approach 1.
        while (tempSum <= tempMax){
            tempValue++;
            tempSum += tempValue;
            System.out.println("tempValue = " + tempValue + ", tempSum = " + tempSum);
        }//of while
        tempSum -= tempValue;

        System.out.println("The sum not exceeding " + tempMax + " is: " + tempSum);

        //Approach 2.
        System.out.println("\r\nAlternative approach.");
        tempValue = 0;
        tempSum = 0;
        while(true){
            tempValue++;
            tempSum += tempValue;
            System.out.println("tempValue = " + tempValue + ", tempSum = " + tempSum);

            if (tempMax < tempSum){
                break;
            }//of if
        }// of while
        tempSum -= tempValue;

        System.out.println("The sum not exceeding " + tempMax + " is: " + tempSum);
    }//of whileStatementTest
}//of class WhileStatement

2、综合任务 

这道练习的代码是比较经典的循环判断比大小,求最大值及最小值并记录对应的下标。

(1)利用随机数函数来生成学生成绩,然后进行比较,这里nextint需要注意返回的范围是左闭右开,取不到参数值本身,题目中说明60分以下视为不合格,也就是总成绩为0,当某行中的三个数字有一个为0时,该总分数为0,当nextint传入的参数值较小时,也就会出现lowerBound(50)加一个较小的随机数值,导致较大概率每个学生都不合格的情况。

(2)循环判断部分最大值最小值的设定比较容易在一些情况下踩坑,例如不清楚输入的数据正负等情况,这里由于实际意义是学生的成绩,所以非负,最大值的初始判断值考研设置为0,最小值判断是指m个学生都是最高分的总和+1,这样就能保证最小值判断时是最大的。 

package basic;

import java.util.Arrays;
import java.util.Random;
/**
 * @author Fan Min minfanphd@163.com.
 **/
public class Task1 {
    /**
     * The entrance of the program.
     *
     * @param args Not used now.
     */
    public static void main(String args[]){
        task1();
    }//of main

    /**
     * Method unit test.
     */
    public static void task1(){
        //Step 1. Generate the data with n students and m courses.
        //Set these values by yourself.
        int n = 10;
        int m = 3;
        int lowerBound = 50;
        int upperBound = 67; // should be 100. I use this value for testing.
        int threshold = 60;

        //Here we have to use an object to generate random numbers.
        Random tempRandom = new Random();
        int[][] data = new int[n][m];
        for (int i = 0; i < n; i++){
            for (int j = 0; j < m; j++){
                data[i][j] = lowerBound + tempRandom.nextInt(upperBound - lowerBound);
            }//of for j
        }//of for i
        System.out.println("The data is:\r\n" + Arrays.deepToString(data));

        //Step 2. Compute the total score of each student.
        int[] totalScores = new int[n];
        for (int i = 0; i < n; i++){
            for (int j = 0;j < m; j++){
                if (data[i][j] < threshold){
                    totalScores[i] = 0;
                    break;
                }// of if
                totalScores[i] += data[i][j];
            }//of for j
        }//of for i

        System.out.println("The total scores are:\r\n" + Arrays.toString(totalScores));

        //Step 3. Find the best and worst student.
        //Typical initialization for index: invalid value.
        int tempBestIndex = -1;
        int tempWorstIndex = -1;
        //Typical initialization for best and worst walues.
        //They must be replaced by valid values.
        int tempBestScore = 0;
        int tempWorstScore = m * upperBound + 1;
        for (int i=0; i<n; i++){
            //Do not consider failed students.
            if (totalScores[i] == 0){
                continue;
            }//of if

            if (tempBestScore < totalScores[i]){
                tempBestScore = totalScores[i];
                tempBestIndex = i;
            }// of if

            //Attention: This if statement cannot be combined with the last one
            //using "else if", because a student can be both the best and the
            //worst. I found this bug while setting upperBound = 65.
            if (tempWorstScore > totalScores[i]){
                tempWorstScore = totalScores[i];
                tempWorstIndex = i;
            }//of if
        }// of for i

        //Step 4. Output the student number and score.
        if (tempBestIndex == -1){
            System.out.println("Cannot find best student. All students have failed");
        }else {
            System.out.println("The best student is No." + tempBestIndex + " with scores: "
            + Arrays.toString(data[tempBestIndex]));
        }//of if

        if (tempWorstIndex == -1){
            System.out.println("Cannot find best student. All students have failed");
        }else {
            System.out.println("The worst student is No." + tempWorstIndex + " with scores: "
                    + Arrays.toString(data[tempWorstIndex]));
        }//of if
    }//of task1
}//of class Task1

3、顺序表(一)

 关于顺序表的创建,其中用到了构造方法当中的无参构造和有参构造,以及Object类下toString的改写,当打印时字符串与我们的变量相加时,系统会自动调用toString方法。

package datastructure.list;

/**
 * @author Fan Min minfanphd@163.com.
 **/
public class SequentialList {
    /**
     * The maximal length of the list. It is a constant.
     */
    public static final int MAX_LENGTH = 10;

    /**
     * The actual length not exceeding MAX_LENGTH. Attention: length is not only
     * the member variable of Sequential list, but also the member variable of
     * Array. In fact, a name can be the member variable of different classes.
     */
    int length;

    /**
     * The data stored in an array.
     */
    int[] data;

    /**
     * Construct an empty sequential list.
     */
    public SequentialList(){
        length = 0;
        data = new int[MAX_LENGTH];
    }//of the first constructor

    /**
     * Construct a sequential list using an array.
     *
     * @param paraArray
     *              The given array. Its length should not exceed MAX_LENGTH. For
     *              simplicity now we do not check it.
     */
    public SequentialList(int[] paraArray){
        data = new int[MAX_LENGTH];
        length = paraArray.length;

        //Copy data.
        for (int i = 0; i < paraArray.length; i++){
            data[i] = paraArray[i];
        }//of for i
    }// of the second constructor

    /**
     * Overrides the method claimed in Object, the superclass of any class.
     */
    public String toString(){
        String resultString = "";

        if (length == 0){
            return "empty";
        }//of if

        for (int i = 0; i < length - 1; i++){
            resultString += data[i] + ", ";
        }//of for i

        resultString += data[length - 1];
//        System.out.println(resultString);
        return resultString;
    }//of toString

    /**
     * Reset to empty.
     */
    public void reset(){
        length = 0;
    }//of reset

    /**
     * The entrance of the program.
     *
     * @param args
     *              Not used now.
     */
    public static void main(String args[]){
        int[] tempArray = {1,4,6,9};
        SequentialList tempFirstList = new SequentialList(tempArray);
        System.out.println("Initialized, the list is: " + tempFirstList.toString());
        System.out.println("Again, the list is: " + tempFirstList);

        tempFirstList.reset();
        System.out.println("After reset, the list is: " + tempFirstList);
    }//of main
}//of class sequentialList

这次学习主要在于语法基础的收尾,综合任务的随机数和循环判断的踩坑点回顾,如有错误请及时联系更正,谢谢!

  • 7
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值