POLAYOR

学校Java Week6

Week6

W6L1

Array

// create an Array
int [] myArray;
myArray = neew int[5];

// 2D Array
int[][] a = new int[3][5]; // 3 rows, 5 columns

Arrays + For Loops

  • Find the maximum in arrays
  • double for-loops
  • ......

Limitations of Arrays

int[] a = new int[4];
a.length;

Default Array value

  • int: 0;
  • Boolean: false;
  • String: null;

Pretty print

System.out.print(x + "\t") ; // 上下能对齐

Overloading

  • you cannot declare two methods with the same signature and different return types.
  • If both methods have the same parameter types, but different return types, then it is not possible.

Primitive Data Type

Reference-type variables store the location of an object in the computer's memory

  • 8 primitive types: byte, short, int, long, float, double, boolean, char
  • Everything else, including arrays and String, is not a primitive type but rather a reference type

Char characters

  • Chars are primitive
  • A char is a Unicode character

String

// Comparison
a.equals(b); // is recommended
a == b; // is not recommended
Useful Method Summary
  • boolean isEmpty()
  • int length()
  • char charAt(i)
  • String substring(int from)
  • String substring(int from, int to)
  • int indexOf(char)
  • int indexOf(String)
  • boolean contains(String s)
  • boolean startsWith(String s)
  • boolean endsWith(String s)
  • boolean equals(String s)
  • boolean equalsIgnoreCase(String s)
  • String toUpperCase()
  • String toLowerCase()

W6L2 ex1

题目

Write a Java method that given a string text, returns true if the string "war" and "peace" appear the same number of times in text.

All input letters are in lowercase.

Test cases :
warAndPeace("there was never a good war, or a bad peace") → true
warAndPeace("war what is it good for") → false

代码

public class W6L2_ex1 {
    public static void main(String[] args) {
        System.out.println(warAndPeace("there was never a good war, or a bad peace"));
        System.out.println(warAndPeace("war what is it good for"));
    }

    public static boolean warAndPeace(String text) {
        int cWar = 0;
        int cPeace = 0;
        String textWar = text;
        String textPeace = text;

        while (textWar.indexOf("war") != -1) {
            cWar++;
            textWar = textWar.substring(textWar.indexOf("war") + 3);
        }

        while (textPeace.indexOf("peace") != -1) {
            cPeace++;
            textPeace = textPeace.substring(textPeace.indexOf("peace") + 5);
        }

        return (cWar == cPeace) ? true : false;
    }
}

W6L2 ex2

题目

You work for a manufacturer that makes a product with a unique ID string to encode the attributes of the product.
The last character of the ID is a check digit which is the sum of the digits '0-9' that appear in the ID, ignoring all other characters, modulo 11, using the character 'X' if the remainder is 10.

Write a Java method that takes an ID string and determines whether or not it is a valid ID number.
Note that an ID string is of length at least 5, uses upper or lower case letters, as well as dashes '-'.

Note that Character.isDigit(char) tests if a char is one of the chars '0', '1', ..., '9'. Also recall that Integer.parseInt(string) converts a string to an int.

Test cases :
isValidID("THMBB7092WD114221") → false
isValidID("A001-606X-17X") → true

代码

public class W6L2_ex2 {
    public static void main(String[] argw) {
        System.out.println(isValidID("THMBB7092WD114221"));
        System.out.println(isValidID("THMBB7092WD114226"));
        System.out.println(isValidID("A001-606X-17X"));
        System.out.println(isValidID("A001_606X-17X"));
    }

    public static boolean isValidID(String id) {

        if (id.length() < 5 || id == null) {
            return false;
        }

        for (int i=0; i < id.length()-1; i++) {
            int j = Integer.valueOf(id.charAt(i));
            if (!((48 <= j && j <= 57) || (65 <= j && j <= 90) || (97 <= j && j <= 122) || (j == 45))) {
                return false;
            }
        }

        int c=0;

        for (int i=0; i < id.length()-1; i++) {
            if (Character.isDigit(id.charAt(i))) {
                c += Integer.parseInt(String.valueOf(id.charAt(i)));
            }
        }

        if (id.charAt(id.length() - 1) == 'X' || id.charAt(id.length() - 1) == 'x') {
            if (c%11 == 10) {
                return true;
            }
        }

        if (48 <= Integer.valueOf(id.charAt(id.length() - 1)) && Integer.valueOf(id.charAt(id.length() - 1)) <= 57) {
            if (c%11 < 10) {
                if (Integer.parseInt(String.valueOf(id.charAt(id.length()-1))) == c%11) {
                    return true;
                }
            }
        }

        return false;
    }
}

W6 CW1 6.1

题目

A sandwich is two pieces of bread with fillings in between (possibly another bread).
Write a Java method that returns the string that is between the first and last appearance of "bread" in the given input string, or returns the string "none" if there are not two pieces of bread.

All input letters are in lowercase.

Test cases :
sandwichFillings("breadtunabread") → "tuna"
sandwichFillings("chipsbreadtunasalad") → "none"

代码

/*      不全面的代码
        String[] beef = input.split("bread");
        for (int i=0; i<beef.length; i++) {
            if (i==0) {
                str_first = beef[i];
            }

            if (i == beef.length-1) {
                str_last = beef[i];
            }
        }
         */

    /*
        if (str_first.equals("")) {
            if (input.indexOf(str_last) == input.length()-str_last.length()) {
                output = input.substring(5, input.length()-5-str_last.length());
                return output;
            } else if (input.indexOf(str_last) == input.length()-str_last.length()-5) {
                output = input.substring(str_first.length()+5, input.length()-5);
                return output;
            }

            if (str_last.equals("")) {
                return "";
            }
        }

        if (input.indexOf(str_first) == 0) {
            if (input.indexOf(str_last) == input.length()-str_last.length()) {
                output = input.substring(str_first.length()+5, input.length()-str_first.length()-str_last.length()-2);
                return output;
            } else if (input.indexOf(str_last) == input.length()-str_last.length()-5) {
                output = input.substring(str_first.length()+5, input.length()-str_first.length()-2);
                return output;
            }
        }
         */
/*
    for (int i=0; i < input.length()-1; i++) {
        int j = Integer.valueOf(input.charAt(i));
        if (!(97 <= j && j <= 122)) {
        return "none";
        }
    }
        */

public class W6_CW1_61 {
    public static void main(String[] args) {
        System.out.println(sandwichFillings("syxbreadasdz iybre adtunabreadziy"));
        System.out.println(sandwichFillings("syxbreadasd-ziybreadtu-nabreadziy"));
        System.out.println(sandwichFillings("syxbreadasdbreadtunabread"));
        System.out.println(sandwichFillings("breadasdbreadtunabreadziy"));
        System.out.println(sandwichFillings("breadasdbreadtunabread"));
        System.out.println(sandwichFillings("sadsabreadse"));
        System.out.println(sandwichFillings("sadsabreadbreadse"));
        System.out.println(sandwichFillings("sadsabreadbreadbreadse"));
        System.out.println(sandwichFillings("breadtunabread"));
        System.out.println(sandwichFillings("chipsbreadtunasalad"));
        System.out.println(sandwichFillings("bread bread"));
        System.out.println(sandwichFillings("breadbreadbread"));
        System.out.println(sandwichFillings("breadbreadbreadbread"));
        System.out.println(sandwichFillings("breadbreadasehuifoahsjkawbreadbread"));

        System.out.println("--");
        System.out.println(sandwichFillings("breadbread"));
        System.out.println("--");

//        System.out.println(sandwichFillings("tuna"));
    }



    public static String sandwichFillings(String input) {

        String output = "";
        if (!input.contains("bread")) {
            return "none";
        }

        String input2 = input;
        input2 = input.substring(input.indexOf("bread")+5);
        if (!input2.contains("bread")) {
            return "none";
        }

        int[] beef_bread = new int[input.length()/5+1];

        int c = 0;

        input2 = input;
        while (input2.indexOf("bread") != -1) {
            if (c==0) {
                beef_bread[c] = input2.indexOf("bread");
                input2 = input2.substring(input2.indexOf("bread") + 5);
                c++;
                continue;
            }
            beef_bread[c] = input2.indexOf("bread")+5+beef_bread[c-1];
            input2 = input2.substring(input2.indexOf("bread") + 5);
            c++;
        }

        if (beef_bread[0] == 0) {
            int i = 0;
            int j = 1;

            while (beef_bread[j] != 0 && j<beef_bread.length) {
                i = j;
                j++;
            }

            output = input.substring(5, beef_bread[i]);
            return output;
        } else {
            int i = 0;
            int j = 1;

            while (beef_bread[j] != 0 && j<beef_bread.length) {
                i = j;
                j++;
            }

            output = input.substring(beef_bread[0]+5, beef_bread[i]);
            return output;
        }

    }
}

W6 CW1 6.2

题目

To create a home budget, you want to find out your net income, which is your income minus your expenses.

Write a Java method that takes an input string and computes the income minus the expenses.
The income components are indicated by numbers; while the expenses from your spending are numbers starting with a minus sign '-'.

The input string may contain lowercase and uppercase letters, as well as other characters.

Note that Character.isDigit(char) tests if a char is one of the chars '0', '1', ..., '9'. Also recall that Integer.parseInt(string) converts a string to an int.

Test cases :
calcNetIncome("salary 15000yuan bonus2000 rent -1000Y") → 16000
calcNetIncome("25000 gross income, -200 water, electricity:-300") → 24500

代码

public class W6_CW1_62 {
    public static void main(String[] args) {
        System.out.println(calcNetIncome("salary 15000yuan bonus2000 rent -1000Y"));
        System.out.println(calcNetIncome("25000 gross income, -200 water, electricity:-300"));
        System.out.println(calcNetIncome(""));
        System.out.println(calcNetIncome("0"));
        System.out.println(calcNetIncome("-"));
        System.out.println(calcNetIncome("q"));
        System.out.println(calcNetIncome("-q"));
        System.out.println(calcNetIncome("1q"));
        System.out.println(calcNetIncome("-1q"));
        System.out.println(calcNetIncome("1-q"));
        System.out.println(calcNetIncome("25000 gross income, -200 water, electricity:-300-900"));
        System.out.println(calcNetIncome("-25000 gross income, -200 water, electricity:-300"));
    }

    public static int calcNetIncome(String input) {
        String t = ""; // 临时变量
        int c = 0; // 计数器

        // 遍历input,判断有几个数字以便确定数组最大长度
        for (int i=0; i< input.length(); i++) {
            if (Character.isDigit(input.charAt(i))) {
                c++;
            }
        }

        int[] moneyAll = new int[c]; // 存放收入与支出,一笔交易占用一个索引
        c = 0;

        for (int i=0; i< input.length(); ) {

            // 情况一:支出
            if ((String.valueOf(input.charAt(i))).equals("-")) {
                t = "-"; // 初始化临时变量
                i++;
                while (i<input.length() && Character.isDigit(input.charAt(i))) { // 先判断i的大小,避免方法索引超限
                    t += input.charAt(i);
                    i++;
                }

                if (t.equals("-")) { // 避免单词连接符占用数组长度
                    continue;
                }

                moneyAll[c] = Integer.parseInt(t);
                c++;

                continue;
            }

            // 情况二:收入
            if (Character.isDigit(input.charAt(i))) {
                t = ""; // 初始化临时变量
                while (i<input.length() && Character.isDigit(input.charAt(i)) && i<input.length()) {
                    t += input.charAt(i);
                    i++;
                }

                moneyAll[c] = Integer.parseInt(t);
                c++;

                continue;
            }

            i++;

        }

        int sum = 0; // 计算净收入

        for (int i=0; i<moneyAll.length; i++) {
            sum += moneyAll[i];
        }

        return sum;
    }
}

posted on 2022-10-21 14:42  POLAYOR  阅读(23)  评论(0编辑  收藏  举报

导航