【问题标题】:Accept a sentence and print the words that have consecutive characters in them接受一个句子并打印其中有连续字符的单词
【发布时间】:2023-03-16 22:59:01
【问题描述】:

接受一个句子并打印其中包含连续字符的单词

输入:嗨,我的狗很顽皮

输出:嗨,淘气

import java.util.*;

public class Program6  {

    public static void main(String args[])
    {
        Scanner sc= new Scanner(System.in);
        System.out.println("Enter a Sentence : ");
        String s=sc.nextLine();
        s=s.toLowerCase();
        int l= s.length();
        s=' '+s+' ';
        int i;char c,d;int a,b,j=0; 
        for (i=0;i<l;i++)
        {
            c=s.charAt(i);
            d=s.charAt(i+1);
            a=c;
            b=d;
            if(d==' ')
             j=i;
            if((a+1)==b)
             System.out.println(s.substring(0,j));
            }
    }
}

它显示类已编译 - 没有语法错误,但输出不正确,它显示了一些不同的东西。

【问题讨论】:

  • 期望的输出是什么?
  • 你应该做一些调试。

标签: java string character


【解决方案1】:

您的代码中存在多个问题,例如,在您的代码中,即使您发现一个单词中的两个连续字符彼此相邻,您也尝试执行子字符串,可能您从未设置过 j,因为您之前从未找到过空格因此您将 0,0 作为参数传递给子字符串方法。

更简单的方法是:

  1. 用一个或多个空格分隔句子
  2. 检查两个连续字符是否相邻。
  3. 如果是,则打印该单词,然后移动到下一个单词(如果有)
  4. 如果没有,则移动到其他角色。

【讨论】:

    【解决方案2】:
     import java.util.*;
    public class Ch8_30
    {
        public static void main(String args[])
        {
         Scanner x= new Scanner(System.in);
         String s;int i=0,b=0,a=0,c=0;
         System.out.println("enter a string");
         s=x.nextLine().toUpperCase();
         String m[]=s.split("\\s");
         for(i=0;i<m.length;i++)
         {
             b=0;
             for(a=0;a<m[i].length();a++)
             {
                 if(a==m[i].length()-1)
                 break;
    
                 if((char)(m[i].charAt(a)+1)==m[i].charAt(a+1))
                 {
                     b++;c++;
                     System.out.println(m[i]);
                     break;
                 }
    
             }     
         }
         System.out.println("no. of words "+c);
        }
    }
    

    【讨论】:

      【解决方案3】:

      试试这个 将字符串转换为小写后-

          s=s+" ";
          l=s.length();
          for(i=0;i<l;i++)
          {
              ch=s.charAt(i);
              if(ch!=' ')
              w=w+ch;
              else
              {
                  word=w;
                  w="";
                  for(j=0;j<word.length()-1;j++)
                  {
                      c=word.charAt(j);
                      d=word.charAt(j+1);
                      if(d==c+1)
                      System.out.print(word+"  ");
                  }
              }
          }
      

      【讨论】:

        猜你喜欢
        • 2015-10-24
        • 1970-01-01
        • 2022-01-01
        • 2014-12-31
        • 2022-12-04
        • 1970-01-01
        • 1970-01-01
        • 2015-04-21
        • 1970-01-01
        相关资源
        最近更新 更多