Java學習筆記(持續更新ing)
1、在讀入字串時: str = sc.nextLine(); //讀入一行
str = sc.next(); // 只是讀入字串
2、在結構體的表示中用類來表示。
//down的地址https://blog.csdn.net/fyp19980304/article/details/80448060 方法一:把要儲存的資料設為私有變數,然後另寫函式對其進行讀寫,set()和get() public class Test { private int x; private int y; public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } } 方法二: 把要儲存的資料設為public變數,在其他主函式類中直接訪問修改。 class Supply implements Comparable<Supply>{ int number; int max; int spend; }
3、Java中保留小數點後2位的方法(轉)
import java.math.BigDecimal; import java.text.DecimalFormat; import java.text.NumberFormat; public class Test { public static void main(String[] args) { double d = 756.2345566; //方法一:最簡便的方法,呼叫DecimalFormat類 DecimalFormat df = new DecimalFormat(".00"); System.out.println(df.format(d)); //方法二:直接通過String類的format函式實現 System.out.println(String.format("%.2f", d)); //方法三:通過BigDecimal類實現 BigDecimal bg = new BigDecimal(d); double d3 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); System.out.println(d3); //方法四:通過NumberFormat類實現 NumberFormat nf = NumberFormat.getNumberInstance(); nf.setMaximumFractionDigits(2); System.out.println(nf.format(d)); } }
4、Split
在java.lang包中有String.split()方法,返回是一個數組
1、如果用“.”作為分隔的話,必須是如下寫法,String.split("\\."),這樣才能正確的分隔開,不能用String.split(".");
2、如果用“|”作為分隔的話,必須是如下寫法,String.split("\\|"),這樣才能正確的分隔開,不能用String.split("|");
“.”和“|”都是轉義字元,必須得加"\\";
3、如果在一個字串中有多個分隔符,可以用“|”作為連字元,比如,“acount=? and uu =? or n=?”,把三個都分隔出來,可以用String.split("and|or");
使用String.split方法分隔字串時,分隔符如果用到一些特殊字元,可能會得不到我們預期的結果。
5、trim():去掉字串首尾的空格。
去掉字串行首和行末的空格。
s = s.trim();
6、replace 字串替換
st = st.replace(s, t);
在Java中,在字串 st 中要將一段子串 s 替換成另一段子串 t,這個時候可以用 replace。
7、 indexOf 查詢
indexOf 有四種用法:
1.indexOf(int ch) 在給定字串中查詢字元(ASCII),找到返回字元陣列所對應的下標找不到返回-1
2.indexOf(String str) 在給定符串中查詢另一個字串。。。
3.indexOf(int ch,int fromIndex)從指定的下標開始查詢某個字元,查詢到返回下標,查詢不到返回-1
4.indexOf(String str,int fromIndex)從指定的下標開始查詢某個字串。。。