Java - 字符串类,扫描程序类

时间:2016-04-19 06:25:26

标签: java string class

如何从输入行读取一个句子(字符串),并打印它是代表一个陈述句(即以句号结尾),询问(以问号结尾)还是感叹号(以...结尾)感叹号)或不是句子(其他任何东西)?

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 ");
  }
}

1 个答案:

答案 0 :(得分:0)

需要使用.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 ");

    }
}