歡迎訪問我的個人網站:http://www.qingshuimonk.com/
2.基本數據類型和基本操作
1. 字符串連接符:將兩個字符串連接起來,如果一個不是字符串,則先將其值轉換爲字符串,再與另一個字符串相連。
PA:在源代碼中,字符串常量不能跨行。
2. 數值直接量:在程序中直接出現的常量值。
3. 默認情況下整形直接量默認爲十進制,八進制用0開頭,十六進制用0X開頭。
4. 浮點數默認爲double型,double型比float型更精確。
5. 條件布爾運算符:&&,||,當判斷一邊的表達式即可確定整個表達式的值後,另外一邊不進行計算。
無條件布爾運算符:&,|,兩邊都要進行計算。
儘量不適用無條件布爾運算符,降低程序執行效率且可能出錯。
6. 從輸入對話框獲取輸入,使用JOptionPane中的showInptutDialog方法,在運行時獲得輸入。
7. showInputDialog的調用方法,Stringstring=JOptionPane.showInputDialog(null,x,y,JOptionPane.QUESTION_MESSAGE),第一個參數總是null,第二個參數是一個提醒用戶的字符串,第三個參數表示輸入對話框的標題,第四個參數可以是JOptionPane.QUESTION_MESSAGE,使對話框顯示圖標。
8. 字符串轉換爲int值,用Integer的parseInt方法:int intValue=Integer.parseInt(intstring);
轉換爲double用Double類的parseDouble方法。
9. 檢測是否是閏年的代碼:
import javax.swing.JOptionPane;
public class IOstudy {
public static void main(String args[]){
//Prompt the user to enter a year
String yearString = JOptionPane.showInputDialog(null,"Enter a year",
"Input an integer",JOptionPane.QUESTION_MESSAGE);
//Convert the string into an int value
int year = Integer.parseInt(yearString);
//Check if the year is a leap year
boolean isLeapyear = ((year%4==0)&&(year%100!=0))||(year%400==0);
//Display the result
if(isLeapyear){
JOptionPane.showMessageDialog(null,year + "is a leap year.","result",JOptionPane.INFORMATION_MESSAGE);
}
else{
JOptionPane.showMessageDialog(null,year + "is not a leap year","result",JOptionPane.INFORMATION_MESSAGE);
}
}
}
11. 格式化輸出:System.out.printf(format,items)
其中format是一個子串和格式描述符構成的字符串
Example:
int count =5;
double amount= 45.56;
system.out.printf(“countis %d and amount is %f”,count,amout);
PS:%b,布爾型;%e,標準科學計數法形式
12. 默認情況下,浮點顯示小數後六位,可以在描述符中指定寬度和精度
%x.yf,x爲浮點數至少的位數(包含小數點),y小數的位數