简体   繁体   English

Java-字符串类,扫描器类

[英]Java - String Class, Scanner Class

How do I read a sentence (string) from a line of input, and print whether it represents a declarative sentence (ie, ending in a period), interrogatory (ending in a question mark), or an exclamation (ending in exclamation point) or is not a sentence (anything else)? 如何从输入行中读取一个句子(字符串),并打印它代表的是陈述性句子(即以句号结尾),疑问句(以问号结尾)还是感叹号(以感叹号结尾)还是不是一个句子(其他)?

import java.util.*;

public class StringDemo {
public static void main(String[] args){
        Scanner console = new Scanner(System.in);

        // enter a string: 
        System.out.println("Enter a string: "); 
        String dog = console.nextLine();
        dog = dog.toUpperCase();
        System.out.println(dog + " has " + dog.length() +
           " letters and starts with " + dog.substring(0, 1));





        // enter another string:
        System.out.println("Enter another string: "); 
        String cat = console.nextLine();
        cat = cat.toUpperCase();
        System.out.println(cat + " has " + cat.length() +
           " letters and starts with " + cat.substring(0, 1)); 

      // check contents here
      if(dog.equals(cat))
          System.out.println("Input Strings are matching ");
      else
          System.out.println("Input Strings are not matching ");
  }
}

Need to use .equals() method to check content equality as below. 需要使用.equals()方法检查内容是否相等,如下所示。

import java.util.*;

public class StringDemo {
public static void main(String[] args) {
            Scanner console = new Scanner(System.in);

            // enter a string: 
            System.out.println("Enter a string: "); 
            String dog = console.nextLine();
            dog = dog.toUpperCase();
            System.out.println(dog + " has " + dog.length() +
               " letters and starts with " + dog.substring(0, 1));





            // enter another string:
            System.out.println("Enter another string: "); 
            String cat = console.nextLine();
            cat = cat.toUpperCase();
            System.out.println(cat + " has " + cat.length() +
               " letters and starts with " + cat.substring(0, 1)); 

           // check contents here
          if(dog.endsWith("?"))
              System.out.println("Input Strings ends in a question mark ");

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM