我需要編寫一個接受字符串的程序,並打印出除去所有元音除外的字符串文本,除非一個字以它開頭。需要打印沒有元音的掃描儀字符串的代碼
我寫的代碼是一半的,但我不明白爲什麼它不會返回整個字符串,並且不會刪除所有的元音。說我輸入短語「理想的財產區」。該程序打印字符串,「Dirlp」而不是「Dsrbl prprty ar」
有人可以告訴我如何改善代碼,使其工作?謝謝!
這裏是我的代碼:
public static void main (String [] args)
{
Scanner in = new Scanner (System.in);
System.out.print ("Enter some text, then hit enter: ");
String text = in.nextLine();
takeOutVowel (text);
System.out.println();
}
static void takeOutVowel (String s)
{
char ch = s.charAt(0); //character to be printed
System.out.print (ch);
int nextCh = 1; //determines the position of the next character
int increase = 1; //increase is how much i will increase by in the for loop; takes the position of vowels into //consideration so they can be skipped
for (int i = 1; i <= s.length(); i += increase)
{
ch = s.charAt (nextCh);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
{
nextCh++;
ch = s.charAt (nextCh);
while (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u');
{
nextCh++;
ch = s.charAt (nextCh);
if (nextCh >= s.length())
{
ch = ' ';
break;
}
}
}
System.out.print (ch);
nextCh++;
ch = s.charAt (nextCh);
if (ch == ' ') //if the previous position was a space, then this will allow for the vowel to be printed
{
System.out.print ("" + ch + s.charAt(nextCh + 1));
nextCh++;
}
increase = nextCh;
}
感謝所有的答案迄今 - 非常有幫助!我不允許使用數組或任何未覆蓋的內容,所以我已將代碼修改爲下面的內容。它編譯罰款,但是當我運行該程序並進入掃描儀的文字,我得到一個消息,說
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 27
at java.lang.String.charAt(String.java:686)
at Vowels.noVowels(Vowels.java:20)
at Vowels.main(Vowels.java:11)
我想不出是什麼問題了。再次感謝您的幫助!
import java.util.*;
class Vowels
{
public static void main (String [] args)
{
Scanner in = new Scanner (System.in);
System.out.print ("Enter some text, then hit enter: ");
String text = in.nextLine();
System.out.println (noVowels(text));
}
static String noVowels (String s)
{
String noVowels = "" + s.charAt(0); //Starts a new string with the first character of the input text
for (int i = 1; i <= s.length(); i++)
{
if (isVowel(s.charAt(i)) && s.charAt(i-1) != ' ') //if the character is a vowel and it's previous character wasn't a space, then this is a vowel to be replaced
{
noVowels = noVowels.concat("");
}
else
{
noVowels = noVowels.concat("" + s.charAt(i));
}
}
return noVowels;
}
static boolean isVowel (char ch)
{
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
{
return true;
}
else
{
return false;
}
}
}
http://stackoverflow.com/questions/4430112/how-do-i-remove-some-characters-from-my-string(我的意思是,你可以只是與每一個元音一個簡單的正則表達式。 ..) – Shiki
如果單詞以元音開頭,那麼您不需要從該單詞中刪除任何元音? – Adarsh
我假設你的索引超出範圍是因爲在'for'循環中你的條件是'i <= s.length();'。假設你的字符串是「hello」 - 長度是5,但是's.charAt(5)'不存在。陣列中的最大位置是4. –