這篇文章將為大家詳細講解有關Java中輸出字符ASCII值的案例分析,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
1. 我們可以通過將字符強轉為int型進行輸出那么在控制臺中我們將會得到字符的ascii值,這里我們使用nextLine()方法來接收字符串,可以接收空格/Tab鍵,使用next()方法則不會接收空格/Tab鍵,但是這里使用nextLine方法不能打印回車鍵的ascii值因為它遇到回車鍵就截止接收字符了
2. 具體的測試代碼如下:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
for(int i = 0; i < s.length(); i++){
System.out.println((int)s.charAt(i));
}
sc.close();
}
}輸入:
0123456789
輸出:

補充知識:Java Integer -128~127
今天刷到了一道題,為什么第一個為true,第二個為false?! ?/p>
System.out.println(Integer.valueOf("100")==Integer.valueOf("100")); //true
System.out.println(Integer.valueOf("200")==Integer.valueOf("200")); //false
研究源碼發現
/**
* Returns a <tt>Integer</tt> instance representing the specified
* <tt>int</tt> value.
* If a new <tt>Integer</tt> instance is not required, this method
* should generally be used in preference to the constructor
* {@link #Integer(int)}, as this method is likely to yield
* significantly better space and time performance by caching
* frequently requested values.
*
* @param i an <code>int</code> value.
* @return a <tt>Integer</tt> instance representing <tt>i</tt>.
* @since 1.5
*/
public static Integer valueOf(int i) {
if(i >= -128 && i <= IntegerCache.high)
return IntegerCache.cache[i + 128];
else
return new Integer(i);
} private static class IntegerCache {
static final int high;
static final Integer cache[];
static {
final int low = -128;
// high value may be configured by property
int h = 127;
if (integerCacheHighPropValue != null) {
// Use Long.decode here to avoid invoking methods that
// require Integer's autoboxing cache to be initialized
int i = Long.decode(integerCacheHighPropValue).intValue();
i = Math.max(i, 127);
// Maximum array size is Integer.MAX_VALUE
h = Math.min(i, Integer.MAX_VALUE - -low);
}
high = h;
cache = new Integer[(high - low) + 1];
int j = low;
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++);
}
private IntegerCache() {}
}valueOf會將常用的值(-128 to 127)cache起來。當i值在這個范圍時,會比用構造方法Integer(int)效率和空間上更好。
關于Java中輸出字符ASCII值的案例分析就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。