如何使用两个字符串方法编写程序?

时间:2017-10-15 20:11:23

标签: java

我正在尝试为我的作业编写一个程序,用于计算单词和句子在相同索引处的相同字符数。

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

我可以使用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();

1 个答案:

答案 0 :(得分: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 + ' ';
    }
}