英文:
Java sentence shortening program doesn't work right
问题
import java.util.Scanner;
public class SentenceShortener {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
String sentence = "";
String sentence2 = "";
String sentence3 = "";
String finalcount = "";
System.out.println("Input sentence ");
sentence = kbd.nextLine();
int space = sentence.indexOf(" ");
System.out.println(sentence.substring(space+1));
sentence2 = sentence.substring(space+1);
int space2 = sentence2.indexOf(" ");
System.out.println(sentence2.substring(space2+1));
sentence3 = sentence2.substring(space2+1);
int space3 = sentence3.indexOf(" ");
System.out.println(sentence3.substring(space3+1));
finalcount = sentence3.substring(space3+1);
System.out.println("Your " + sentence.length() + " character long sentence was shortened to " + finalcount.length() + " characters.");
}
}
英文:
import java.util.Scanner;
public class SentenceShortener {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
String sentence = "";
String sentence2 = "";
String sentence3 = "";
String finalcount = "";
System.out.println("Input sentence ");
sentence = kbd.nextLine();
int space = sentence.indexOf(" ");
System.out.println(sentence.substring(space+1));
sentence2 = sentence.substring(space+1);
int space2 = sentence.indexOf(" ");
System.out.println(sentence2.substring(space2+1));
sentence3 = sentence2.substring(space2+1);
int space3 = sentence2.indexOf(" ");
System.out.println(sentence3.substring(space3+1));
finalcount = sentence3.substring(space3+1);
System.out.println("Your " + sentence.length() + " character long sentence was shortened to " + finalcount.length() + " characters.");
}
}
I created a program that should shorten four word sentences and longer down to decreasingly shorter "sentences" and counts how many characters you shortened the sentence to.
Here is how it should work:
Input sentence
The car runs good.
car runs good.
runs good.
good.
Your 18 character long sentence was shortened to 6 characters.
How it actually runs:
Input sentence
The car runs good.
car runs good.
runs good.
good.
Your 18 character long sentence was shortened to 6 characters.
Another run:
Input sentence
Why is it raining?
is it raining?
t raining?
aining?
Your 18 character long sentence was shortened to 7 characters.
I'm a beginner with Java.
答案1
得分: 0
逻辑判断空格的索引不正确。
尝试修改你的代码如下:
int space2 = sentence2.indexOf(" ");
int space3 = sentence3.indexOf(" ");
英文:
Logic to determine index of space is incorrect.
Try modifying your code to have
int space2 = sentence2.indexOf(" ");
int space3 = sentence3.indexOf(" ");
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论