确定。所以我正在尝试运行一个程序,但它并没有那么好用。我想我很接近,却错过了一步。
我要求用户输入一个短语(完全随机),然后我要求他们输入另一个短语,即三个单词,所有单词都在一起。该程序的目标是打印出第一个短语,但在第一个位置的第二个短语中具有第三个单词的位置。我还希望得到第一和第三字。
User input : My name is George
user input: name is George
desired output: my GEORGE is NAME
这就是我所拥有的。
import java.util.Scanner;
public class Assign3 {
public static void main(String[] args) {
String one, two, three,four, five,six,seven,eight;
Scanner kbrd = new Scanner(System.in);
System.out.println("please enter a phrase, and then pick three words that you want to switch");
one= kbrd.nextLine();
two= kbrd.next();
three = kbrd.next();
four = kbrd.next();
seven = two+three+four;
System.out.println(one.indexOf(two));
System.out.println(one.lastIndexOf(four));
five = four.toUpperCase()+three+two.toUpperCase();
System.out.println(five);
eight = one.replace(seven,five);
System.out.println(eight);
}
}
答案 0 :(得分:0)
你几乎得到了你所缺少的几个空格,因为它没有找到你的字符串并替换它。
新代码应如下所示:
public static void main(String[] args) {
String one, two, three,four, five,six,seven,eight;
Scanner kbrd = new Scanner(System.in);
System.out.println("please enter a phrase, and then pick three words that you want to switch");
one= kbrd.nextLine();
two= kbrd.next()+" "; // Added space
three = kbrd.next()+" "; // Added space
four = kbrd.next()+" "; // Added space
seven = two+three+four;
System.out.println(one.indexOf(two));
System.out.println(one.lastIndexOf(four));
five = four.toUpperCase()+three+two.toUpperCase();
System.out.println(five);
eight = one.replace(seven.trim(),five.trim()); // timing the last space
System.out.println(eight);
}
输出:
please enter a phrase, and then pick three words that you want to switch
My name is George
name is George
3
-1
GEORGE is NAME
My GEORGE is NAME