⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 exercise7_3.java

📁 Introduction to java programming 一书中所有编程练习部分的源码
💻 JAVA
字号:
// Exercise7_3.java: Check whether the first string is a substring
// of the second string
import javax.swing.JOptionPane;

public class Exercise7_3 {
  public static void main(String[] args) {
    // Prompt the user to enter two strings
    String first = JOptionPane.showInputDialog(
      null, "Enter the first string:",
      "Exercise7_3 Input", JOptionPane.QUESTION_MESSAGE);

    String second = JOptionPane.showInputDialog(
      null, "Enter the second string:",
      "Exercise7_3 Input", JOptionPane.QUESTION_MESSAGE);

    if (isSubstring(first, second)) {
      System.out.println(first + " is a substring of " + second);
    }
    else {
      System.out.println(first + " is not a substring of " + second);
    }
  }

  /**Check if the first string is a substring of the second string*/
  public static boolean isSubstring(String first, String second) {
    int remainingLength = second.length();
    int startingIndex = 0;

    // Note toWhile is a label. You can use break with a label
    // attached.
    toWhile: while (first.length() <= remainingLength) {
      // What is wrong if the following line is used
      // for (int i=startingIndex; i<=first.length(); i++)
      for (int i = 0; i < first.length(); i++) {
        if (first.charAt(i) != second.charAt(startingIndex+i)) {
          startingIndex++;
          remainingLength--;
          continue toWhile;
        }
      }

      return true;
    }

    return false;
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -