Scanner sc= new Scanner(System.in);
System.out.println("Enter A Line");
String S=sc.nextLine();
byte[] barr=S.getBytes(/* "US-ASCII" */); //I believe by default it's this? but not 100% sure about it need to check documentation.
for(int z=0;z<barr.length;z++){
if(barr[z]!=32){ //Add this - if the char is not ' '
System.out.println(barr[z]);
}
}
這應該成爲你在做同樣的目的 - 除非你想申請的charAt()方法的使用。
重新審視您的代碼,我瞭解您正在嘗試執行的操作,並想告訴您爲什麼會出現當前錯誤(如果您不想使用上述方法並自行解決此問題)! 。正如@Pshemo所提到的,你被困在一個無限循環中,因爲while循環不斷檢查ch是否不等於'',而ch值不變。因此,舉例來說,如果我輸入的一行:「你好」到你的代碼,當我編譯它:
//S = "Hello"
for(int i=0;i<S.length();i++){
ch=S.charAt(i); // ch = 'H'
while(ch!=' '){ //Checks if ch is NOT EQUAL to ' ' -- returns true
str=str+ch; // '' = '' + ' '. Now str = ' '
}
//Now it will loop again because it will check if ch is NOT EQUAL to ' ', which is again true.
//Your str variable will now equal ' '. And the loop again continues infinitely.
編輯:所以,如果你想在一個句子內拿到字的ASCII值存在的方法字符串類稱爲public String[] split(String regex)
。此方法返回一個String[]
並將您給出的正則表達式分割給定的String。所以
String s = "boo:and:foo";
/*Created a variable called stringContainer that will reference String[] (Currently references null)*/
String[] stringContainer;
/*My variable now references the SERIES of strings that come from splitting the phrase "boo:and:foo"*/
stringContainer = s.split(":"); //Please note that i called the split method using my original string s (which holds "boo:and:foo")
System.out.println(stringContainer[0]); //Prints out "boo"
System.out.println(stringContainer[1]); //Prints out "and"
System.out.println(stringContainer[2]); //prints out "foo"
,你可以看到你可以在給定字符串分割成一系列的string對象:
例如(從文檔以這樣)。現在,你可以把在for循環通過getBytes方法本身獲得其ASCII值:
for(String stringInArray : stringContainer){ //For each string in String[]...
byte[] barr = stringInArray.getBytes("US-ASCII"); //Get the string's byte value and store in barr...
for(byte b : barr){ //For each byte in byte[]...
//Note: I used print instead of println here because I don't want it to go to next line yet
System.out.print(b + ", "); //Print out the byte value + ", "
}
//After the whole word's byte value has been printed out, go to new line
System.out.println();
}
'ch'不'而(!CH =」「){海峽= STR + CH變更; 「所以你最終陷入無限循環。 – Pshemo
無論如何,你需要知道縮進是重要的。它使我們可以更容易地閱讀代碼並查看適當的範圍。大多數編輯器都有縮進代碼的工具。 – Pshemo
我認爲你的問題是你的while(ch!='')應該是一個if(ch!='')沒有點循環的單個項目;) –