JAVA代碼查錯(cuò)
1.
abstract class Name {
private String name;
public abstract boolean isStupidName(String name) { }
}
大俠們,這有何錯(cuò)誤?
答案: 錯(cuò)。abstract method必須以分號(hào)結(jié)尾,且不帶花括號(hào)。
2.
public class Something {
void doSomething () {
private String s = "";
int l = s.length();
}
}
有錯(cuò)嗎?
答案: 錯(cuò)。局部變量前不能放置任何訪問修飾符 (private,public,和protected)。final可以用來修飾局部變量
(final如同abstract和strictfp,都是非訪問修飾符,strictfp只能修飾class和method而非variable)。
3.
abstract class Something {
private abstract String doSomething ();
}
這好像沒什么錯(cuò)吧?
答案: 錯(cuò)。abstract的methods不能以private修飾。abstract的methods就是讓子類implement(實(shí)現(xiàn))具體細(xì)節(jié)的,怎么可以用private把a(bǔ)bstract
method封鎖起來呢? (同理,abstract method前不能加final)。
4.
public class Something {
public int addOne(final int x) {
return ++x;
}
}
這個(gè)比較明顯。
答案: 錯(cuò)。int x被修飾成final,意味著x不能在addOne method中被修改。
5.
public class Something {
public static void main(String[] args) {
Other o = new Other();
new Something().addOne(o);
}
public void addOne(final Other o) {
o.i++;
}
}
class Other {
public int i;
}
和上面的很相似,都是關(guān)于final的問題,這有錯(cuò)嗎?
答案: 正確。在addOne method中,參數(shù)o被修飾成final。如果在addOne method里我們修改了o的reference
(比如: o = new Other(),那么如同上例這題也是錯(cuò)的。但這里修改的是o的member vairable
(成員變量),而o的reference并沒有改變。
6.
class Something {
int i;
public void doSomething() {
System.out.println("i = " + i);
}
}
有什么錯(cuò)呢? 看不出來啊。
答案: 正確。輸出的是"i = 0"。int i屬於instant variable (實(shí)例變量,或叫成員變量)。instant variable有default value。int的default value是0。
7.
class Something {
final int i;
public void doSomething() {
System.out.println("i = " + i);
}
}
和上面一題只有一個(gè)地方不同,就是多了一個(gè)final。這難道就錯(cuò)了嗎?
答案: 錯(cuò)。final int i是個(gè)final的instant variable (實(shí)例變量,或叫成員變量)。final的instant variable沒有default value,必須在constructor (構(gòu)造器)結(jié)束之前被賦予一個(gè)明確的值??梢孕薷臑?final int i = 0;"。
8.
public class Something {
public static void main(String[] args) {
Something s = new Something();
System.out.println("s.doSomething() returns " + doSomething());
}
public String doSomething() {
return "Do something ...";
}
}
看上去很完美。
答案: 錯(cuò)。看上去在main里call doSomething沒有什么問題,畢竟兩個(gè)methods都在同一個(gè)class里。但仔細(xì)看,main是static的。static method不能直接call non-static methods??筛某?System.out.println("s.doSomething() returns " + s.doSomething());"。同理,static method不能訪問non-static instant variable。
9.
此處,Something類的文件名叫OtherThing.java
class Something {
private static void main(String[] something_to_do) {
System.out.println("Do something ...";
}
}
這個(gè)好像很明顯。
答案: 正確。從來沒有人說過Java的Class名字必須和其文件名相同。但public class的名字必須和文件名相同。
10.
interface A{
int x = 0;
}
class B{
int x =1;
}
class C extends B implements A {
public void pX(){
System.out.println(x);
}
public static void main(String[] args) {
new C().pX();
}
}
答案:錯(cuò)誤。在編譯時(shí)會(huì)發(fā)生錯(cuò)誤(錯(cuò)誤描述不同的JVM有不同的信息,意思就是未明確的x調(diào)用,兩個(gè)x都匹配(就象在同時(shí)import java.util和java.sql兩個(gè)包時(shí)直接聲明Date一樣)。對(duì)于父類的變量,可以用super.x來明確,而接口的屬性默認(rèn)隱含為 public static final.所以可以通過A.x來明確。
11.
interface Playable {
void play();
}
interface Bounceable {
void play();
}
interface Rollable extends Playable, Bounceable {
Ball ball = new Ball("PingPang";
}
class Ball implements Rollable {
private String name;
public String getName() {
return name;
}
public Ball(String name) {
this.name = name;
}
public void play() {
ball = new Ball("Football";
System.out.println(ball.getName());
}
}
這個(gè)錯(cuò)誤不容易發(fā)現(xiàn)。
答案: 錯(cuò)。"interface Rollable extends Playable, Bounceable"沒有問題。interface可繼承多個(gè)interfaces,所以這里沒錯(cuò)。問題出在interface Rollable里的"Ball ball = new Ball("PingPang";"。任何在interface里聲明的interface variable (接口變量,也可稱成員變量),默認(rèn)為public static final。也就是說"Ball ball = new Ball("PingPang";"實(shí)際上是"public static final Ball ball = new Ball("PingPang";"。在Ball類的Play()方法中,"ball = new Ball("Football";"改變了ball的reference,而這里的ball來自Rollable interface,Rollable interface里的ball是public static final的,final的object是不能被改變r(jià)eference的。因此編譯器將在"ball = new Ball("Football";"這里顯示有錯(cuò)。
JAVA編程題
1.現(xiàn)在輸入n個(gè)數(shù)字,以逗號(hào),分開;然后可選擇升或者降序排序;按提交鍵就在另一頁面顯示按什么排序,結(jié)果為,提供reset
import java.util.*;
public class bycomma{
public static String[] splitStringByComma(String source){
if(source==null||source.trim().equals("")
return null;
StringTokenizer commaToker = new StringTokenizer(source,",";
String[] result = new String[commaToker.countTokens()];
int i=0;
while(commaToker.hasMoreTokens()){
result[i] = commaToker.nextToken();
i++;
}
return result;
}
public static void main(String args[]){
String[] s = splitStringByComma("5,8,7,4,3,9,1";
int[] ii = new int[s.length];
for(int i = 0;i<s.length;i++){
ii[i] =Integer.parseInt(s[i]);
}
Arrays.sort(ii);
//asc
for(int i=0;i<s.length;i++){
System.out.println(ii[i]);
}
//desc
for(int i=(s.length-1);i>=0;i--){
System.out.println(ii[i]);
}
}
}
2.金額轉(zhuǎn)換,阿拉伯?dāng)?shù)字的金額轉(zhuǎn)換成中國(guó)傳統(tǒng)的形式如:(¥1011)->(一千零一拾一元整)輸出。
package test.format;
import java.text.NumberFormat;
import java.util.HashMap;
public class SimpleMoneyFormat {
public static final String EMPTY = "";
public static final String ZERO = "零";
public static final String ONE = "壹";
public static final String TWO = "貳";
public static final String THREE = "叁";
public static final String FOUR = "肆";
public static final String FIVE = "伍";
public static final String SIX = "陸";
public static final String SEVEN = "柒";
public static final String EIGHT = "捌";
public static final String NINE = "玖";
public static final String TEN = "拾";
public static final String HUNDRED = "佰";
public static final String THOUSAND = "仟";
public static final String TEN_THOUSAND = "萬";
public static final String HUNDRED_MILLION = "億";
public static final String YUAN = "元";
public static final String JIAO = "角";
public static final String FEN = "分";
public static final String DOT = ".";
private static SimpleMoneyFormat formatter = null;
private HashMap chineseNumberMap = new HashMap();
private HashMap chineseMoneyPattern = new HashMap();
private NumberFormat numberFormat = NumberFormat.getInstance();
private SimpleMoneyFormat() {
numberFormat.setMaximumFractionDigits(4);
numberFormat.setMinimumFractionDigits(2);
numberFormat.setGroupingUsed(false);
chineseNumberMap.put("0", ZERO);
chineseNumberMap.put("1", ONE);
chineseNumberMap.put("2", TWO);
chineseNumberMap.put("3", THREE);
chineseNumberMap.put("4", FOUR);
chineseNumberMap.put("5", FIVE);
chineseNumberMap.put("6", SIX);
chineseNumberMap.put("7", SEVEN);
chineseNumberMap.put("8", EIGHT);
chineseNumberMap.put("9", NINE);
chineseNumberMap.put(DOT, DOT);
chineseMoneyPattern.put("1", TEN);
chineseMoneyPattern.put("2", HUNDRED);
chineseMoneyPattern.put("3", THOUSAND);
chineseMoneyPattern.put("4", TEN_THOUSAND);
chineseMoneyPattern.put("5", TEN);
chineseMoneyPattern.put("6", HUNDRED);
chineseMoneyPattern.put("7", THOUSAND);
chineseMoneyPattern.put("8", HUNDRED_MILLION);
}
public static SimpleMoneyFormat getInstance() {
if (formatter == null)
formatter = new SimpleMoneyFormat();
return formatter;
}
public String format(String moneyStr) {
checkPrecision(moneyStr);
String result;
result = convertToChineseNumber(moneyStr);
result = addUnitsToChineseMoneyString(result);
return result;
}
public String format(double moneyDouble) {
return format(numberFormat.format(moneyDouble));
}
public String format(int moneyInt) {
return format(numberFormat.format(moneyInt));
}
public String format(long moneyLong) {
return format(numberFormat.format(moneyLong));
}
public String format(Number moneyNum) {
return format(numberFormat.format(moneyNum));
}
private String convertToChineseNumber(String moneyStr) {
String result;
StringBuffer cMoneyStringBuffer = new StringBuffer();
for (int i = 0; i < moneyStr.length(); i++) {
cMoneyStringBuffer.append(chineseNumberMap.get(moneyStr.substring(i, i + 1)));
}
//拾佰仟萬億等都是漢字里面才有的單位,加上它們
int indexOfDot = cMoneyStringBuffer.indexOf(DOT);
int moneyPatternCursor = 1;
for (int i = indexOfDot - 1; i > 0; i--) {
cMoneyStringBuffer.insert(i, chineseMoneyPattern.get(EMPTY + moneyPatternCursor));
moneyPatternCursor = moneyPatternCursor == 8 ? 1 : moneyPatternCursor + 1;
}
String fractionPart = cMoneyStringBuffer.substring(cMoneyStringBuffer.indexOf(".");
cMoneyStringBuffer.delete(cMoneyStringBuffer.indexOf(".", cMoneyStringBuffer.length());
while (cMoneyStringBuffer.indexOf("零拾" != -1) {
cMoneyStringBuffer.replace(cMoneyStringBuffer.indexOf("零拾", cMoneyStringBuffer.indexOf("零拾" + 2, ZERO);
}
while (cMoneyStringBuffer.indexOf("零佰" != -1) {
cMoneyStringBuffer.replace(cMoneyStringBuffer.indexOf("零佰", cMoneyStringBuffer.indexOf("零佰" + 2, ZERO);
}
while (cMoneyStringBuffer.indexOf("零仟" != -1) {
cMoneyStringBuffer.replace(cMoneyStringBuffer.indexOf("零仟", cMoneyStringBuffer.indexOf("零仟" + 2, ZERO);
}
while (cMoneyStringBuffer.indexOf("零萬" != -1) {
cMoneyStringBuffer.replace(cMoneyStringBuffer.indexOf("零萬", cMoneyStringBuffer.indexOf("零萬" + 2, TEN_THOUSAND);
}
while (cMoneyStringBuffer.indexOf("零億" != -1) {
cMoneyStringBuffer.replace(cMoneyStringBuffer.indexOf("零億", cMoneyStringBuffer.indexOf("零億" + 2, HUNDRED_MILLION);
}
while (cMoneyStringBuffer.indexOf("零零" != -1) {
cMoneyStringBuffer.replace(cMoneyStringBuffer.indexOf("零零", cMoneyStringBuffer.indexOf("零零" + 2, ZERO);
}
if (cMoneyStringBuffer.lastIndexOf(ZERO) == cMoneyStringBuffer.length() - 1)
cMoneyStringBuffer.delete(cMoneyStringBuffer.length() - 1, cMoneyStringBuffer.length());
cMoneyStringBuffer.append(fractionPart);
result = cMoneyStringBuffer.toString();
return result;
}
private String addUnitsToChineseMoneyString(String moneyStr) {
String result;
StringBuffer cMoneyStringBuffer = new StringBuffer(moneyStr);
int indexOfDot = cMoneyStringBuffer.indexOf(DOT);
cMoneyStringBuffer.replace(indexOfDot, indexOfDot + 1, YUAN);
1. 以下三條輸出語句分別輸出什么?[C易]
char str1[] = "abc";
char str2[] = "abc";
const char str3[] = "abc";
const char str4[] = "abc";
const char* str5 = "abc";
const char* str6 = "abc";
cout << boolalpha << ( str1==str2 << endl; // 輸出什么?
cout << boolalpha << ( str3==str4 << endl; // 輸出什么?
cout << boolalpha << ( str5==str6 << endl; // 輸出什么?
13. 非C++內(nèi)建型別 A 和 B,在哪幾種情況下B能隱式轉(zhuǎn)化為A?[C++中等]
答:
a. class B : public A { …… } // B公有繼承自A,可以是間接繼承的
b. class B { operator A( ; } // B實(shí)現(xiàn)了隱式轉(zhuǎn)化為A的轉(zhuǎn)化
c. class A { A( const B& ; } // A實(shí)現(xiàn)了non-explicit的參數(shù)為B(可以有其他帶默認(rèn)值的參數(shù))構(gòu)造函數(shù)
d. A& operator= ( const A& ; // 賦值操作,雖不是正宗的隱式類型轉(zhuǎn)換,但也可以勉強(qiáng)算一個(gè)
12. 以下代碼中的兩個(gè)sizeof用法有問題嗎?[C易]
void UpperCase( char str[] // 將 str 中的小寫字母轉(zhuǎn)換成大寫字母
{
for( size_t i=0; i<sizeof(str)/sizeof(str[0]); ++i
if( 'a'<=str[i] && str[i]<='z'
str[i] -= ('a'-'A' ;
}
char str[] = "aBcDe";
cout << "str字符長(zhǎng)度為: " << sizeof(str)/sizeof(str[0]) << endl;
UpperCase( str ;
cout << str << endl;
7. 以下代碼有什么問題?[C難]
void char2Hex( char c // 將字符以16進(jìn)制表示
{
char ch = c/0x10 + '0'; if( ch > '9' ch += ('A'-'9'-1);
char cl = c%0x10 + '0'; if( cl > '9' cl += ('A'-'9'-1);
cout << ch << cl << ' ';
}
char str[] = "I love 中國(guó)";
for( size_t i=0; i<strlen(str); ++i
char2Hex( str[i] ;
cout << endl;
4. 以下代碼有什么問題?[C++易]
struct Test
{
Test( int { }
Test() { }
void fun() { }
};
void main( void
{
Test a(1);
a.fun();
Test b();
b.fun();
}
5. 以下代碼有什么問題?[C++易]
cout << (true?1:"1" << endl;
8. 以下代碼能夠編譯通過嗎,為什么?[C++易]
unsigned int const size1 = 2;
char str1[ size1 ];
unsigned int temp = 0;
cin >> temp;
unsigned int const size2 = temp;
char str2[ size2 ];
9. 以下代碼中的輸出語句輸出0嗎,為什么?[C++易]
struct CLS
{
int m_i;
CLS( int i : m_i(i) { }
CLS()
{
CLS(0);
}
};
CLS obj;
cout << obj.m_i << endl;
10. C++中的空類,默認(rèn)產(chǎn)生哪些類成員函數(shù)?[C++易]
答:
class Empty
{
public:
Empty(); // 缺省構(gòu)造函數(shù)
Empty( const Empty& ; // 拷貝構(gòu)造函數(shù)
~Empty(); // 析構(gòu)函數(shù)
Empty& operator=( const Empty& ; // 賦值運(yùn)算符
Empty* operator&(); // 取址運(yùn)算符
const Empty* operator&() const; // 取址運(yùn)算符 const
};
3. 以下兩條輸出語句分別輸出什么?[C++難]
float a = 1.0f;
cout << (int)a << endl;
cout << (int&a << endl;
cout << boolalpha << ( (int)a == (int&a << endl; // 輸出什么?
float b = 0.0f;
cout << (int)b << endl;
cout << (int&b << endl;
cout << boolalpha << ( (int)b == (int&b << endl; // 輸出什么?
2. 以下反向遍歷array數(shù)組的方法有什么錯(cuò)誤?[STL易]
vector array;
array.push_back( 1 ;
array.push_back( 2 ;
array.push_back( 3 ;
for( vector::size_type i=array.size()-1; i>=0; --i // 反向遍歷array數(shù)組
{
cout << array[i] << endl;
}
6. 以下代碼有什么問題?[STL易]
typedef vector IntArray;
IntArray array;
array.push_back( 1 ;
array.push_back( 2 ;
array.push_back( 2 ;
array.push_back( 3 ;
// 刪除array數(shù)組中所有的2
for( IntArray::iterator itor=array.begin(); itor!=array.end(); ++itor
{
if( 2 == *itor array.erase( itor ;
}
11. 寫一個(gè)函數(shù),完成內(nèi)存之間的拷貝。[考慮問題是否全面]
答:
void* mymemcpy( void *dest, const void *src, size_t count
{
char* pdest = static_cast<char*>( dest ;
const char* psrc = static_cast<const char*>( src ;
if( pdest>psrc && pdest<psrc+cout 能考慮到這種情況就行了
{
for( size_t i=count-1; i!=-1; --i
pdest[i] = psrc[i];
}
else
{
for( size_t i=0; i<count; ++i
pdest[i] = psrc[i];
}
return dest;
}
int main( void
{
char str[] = "0123456789";
mymemcpy( str+1, str+0, 9 ;
cout << str << endl;
system( "Pause" ;
return 0;
}