问题描述
ORIGINAL QUESTION IS----用java编写一个程序,输入一个只以!结尾的句子。要么 ? . 句子中的每个单词都由一个空格分隔。将句子转换为大写并删除多余的空格,以便每个单词仅由一个空格分隔。打印无效输入的消息。
package OMG;
import java.util.Scanner;
public class Trimmer_new
{
String Trim(String s)
{
s=s.trim();
String ans="";
int k=0;
s=s+" ";
for(int i=1;i<=s.length();i++)
{
if(s.charat(k)!= ' ')
{
char g=s.charat(k);
ans=ans+g;
k++;
}
else
{
while(s.charat(k)==' ')
{
k++;
}
ans=ans+" ";
k++;
}
}
ans.trim();
return ans;
}
public static void main(String[]args)
{
Scanner sc=new Scanner(system.in);
System.out.print("Enter a sentance ending only with '!' or '?': ");
String a=sc.next();
if(a.endsWith("!")==true||a.endsWith("?")==false)
{
Trimmer_new ob= new Trimmer_new();
System.out.println("Trimmed sentence: "+ob.Trim(a));
}
else
{
System.out.println("error");
}
sc.close();
}
}
但在运行时抛出异常:
(我在 Eclipse IDE 这样做)
解决方法
有两个问题。首先你永远不会在增加 K++ 时进行检查,第二你没有使用 i 即使你不能使用 i 值作为 i=s.length();你总是需要使用直到 -1 因为数组从 0 开始。
更好的选择是:
String result = Arrays.stream(input.split(" ")).filter(p-> p.length()>0).map(p-> p.trim()).collect(Collectors.joining(" "));