2017-10-15 53 views
-3

我正在尝试为我的作业编写一个计算程序,该程序计算同一索引处的单词和句子的相同字符数。如何使用两个字符串方法编写程序?

重点是用户写一个句子和一个单词,程序从相同的索引计算相同的字符并打印它的编号。但是,如果单词比句子短,我必须将单词空格向右滑动并重复,直到单词的长度超过句子的长度。

而且我被允许使用length和charAt作为字符串方法。我找不到最好的写作方式,我被困住了。

import java.util.Scanner; 

public class Question1 { 

    public static void main(String[] args) { 

      Scanner keyboard = new Scanner(System.in); 

      // asking a sentence from user 
      System.out.println("Lütfen bir cümle giriniz."); 
      String sentence = keyboard.nextLine(); 

      //asking a word from user 
      System.out.println("Lütfen bir kelime giriniz."); 
      String word = keyboard.next(); 

      int sentenceLength = sentence.length(); 
      int wordLength = word.length(); 

      for (wordLength = 1; wordLength <= sentenceLength; wordLength++); 

      word.length(); 

回答

0

用while来做。

import java.util.Scanner; 

public class Main { 
    public static final void main(String args[]) 
    { 
     String word, sent; 
     Scanner sc = new Scanner(System.in); 
     System.out.print("sent->"); 
     sent=sc.nextLine(); 
     System.out.print("word->"); 
     word=sc.nextLine(); 
     while(word.length()<sent.length()) 
      word = word + ' '; 
    } 
} 
相关问题