首页 > Java——基础

Java——基础

1.数据类型

int,short,byte,long

double,float

char,String

2.变量

int var;
var = 12;
int var1 = 12;

final int v1 = 0; //常量

C/C++变量的声明和定义是分开的,JAVA不区分。

//c/c++
extern int a;    //声明
int a = 0;        //定义

 3.运算符

JAVA的运算符、类型强制转化与C相似。

 4.枚举

enum Size {SMALL,MIDIUM,LARGE};

5.字符串

//定义
String e = "";
String greeting = "hello";//子串
String greeting = "hello";
String s = greeting.substring(0,3);//拼接
String expletive = "Expletive";
String pg = "deleted";
String msg = expletive + pg;
String msg1 =expletive + 1;
String all = String.join("/","S","M","L","XL");    //"S/M/L/XL"//不可修改
String str = "Help";
str = str.substring(0,3) + "p!";    //Help!//检查字符串相等
s.equals(t);
"Help".equals(greeting);
"Hello".equalsIgnoreCase("help");//空串和null
if(str.length() == 0)if(str.equals(""))if(str == null)

6.构建字符串

StringBuilder builder = new StringBuilder();
builder.append(ch);        //append a charactor
builder.append(str);    //append a string

7.输入输出

import java.util.*;/*** This program demonstrates console input.* @version 1.10 2004-02-10* @author Cay Horstmann*/
public class InputTest
{public static void main(String[] args){Scanner in = new Scanner(System.in);// get first inputSystem.out.print("What is your name? ");String name = in.nextLine();// get second inputSystem.out.print("How old are you? ");int age = in.nextInt();// display output on consoleSystem.out.println("Hello, " + name + ". Next year, you'll be " + (age + 1));}
}

读取密码

Console cons = System.console();
String username = cons.readLine("User name:");
char[] passwd = cons.readPassword("Password:");

8.控制流程

控制流程与C相似

9.大数值计算

import java.math.*;
import java.util.*;/*** This program uses big numbers to compute the odds of winning the grand prize in a lottery.* @version 1.20 2004-02-10* @author Cay Horstmann*/
public class BigIntegerTest
{public static void main(String[] args){Scanner in = new Scanner(System.in);System.out.print("How many numbers do you need to draw? ");int k = in.nextInt();System.out.print("What is the highest number you can draw? ");int n = in.nextInt();/** compute binomial coefficient n*(n-1)*(n-2)*...*(n-k+1)/(1*2*3*...*k)*/BigInteger lotteryOdds = BigInteger.valueOf(1);for (int i = 1; i <= k; i++)lotteryOdds = lotteryOdds.multiply(BigInteger.valueOf(n - i + 1)).divide(BigInteger.valueOf(i));System.out.println("Your odds are 1 in " + lotteryOdds + ". Good luck!");}
}

10.数组

import java.util.*;/*** This program demonstrates array manipulation.* @version 1.20 2004-02-10* @author Cay Horstmann*/
public class LotteryDrawing
{public static void main(String[] args){Scanner in = new Scanner(System.in);System.out.print("How many numbers do you need to draw? ");int k = in.nextInt();System.out.print("What is the highest number you can draw? ");int n = in.nextInt();// fill an array with numbers 1 2 3 . . . nint[] numbers = new int[n];for (int i = 0; i < numbers.length; i++)numbers[i] = i + 1;// draw k numbers and put them into a second arrayint[] result = new int[k];for (int i = 0; i < result.length; i++){// make a random index between 0 and n - 1int r = (int) (Math.random() * n);// pick the element at the random locationresult[i] = numbers[r];// move the last element into the random locationnumbers[r] = numbers[n - 1];n--;}// print the sorted array
      Arrays.sort(result);System.out.println("Bet the following combination. It'll make you rich!");for (int r : result)System.out.println(r);}
}

注意:

Array.toSring()

Array.copyof()

Array.copyOfRange()

Array.sort()

Array.binarySearch()

Array.fill()

Array.equals()

11.类型

对象和对象变量

Data deadline;     //声明一个变量,但是该变量没有引用任何对象
deadline = new Data();    //初始化变量

自定义类

import java.time.*;/*** This program tests the Employee class.* @version 1.12 2015-05-08* @author Cay Horstmann*/
public class EmployeeTest
{public static void main(String[] args){// fill the staff array with three Employee objectsEmployee[] staff = new Employee[3];staff[0] = new Employee("Carl Cracker", 75000, 1987, 12, 15);staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);staff[2] = new Employee("Tony Tester", 40000, 1990, 3, 15);// raise everyone's salary by 5%for (Employee e : staff)e.raiseSalary(5);// print out information about all Employee objectsfor (Employee e : staff)System.out.println("name=" + e.getName() + ",salary=" + e.getSalary() + ",hireDay="+ e.getHireDay());}
}class Employee
{private String name;private double salary;private LocalDate hireDay;public Employee(String n, double s, int year, int month, int day){name = n;salary = s;hireDay = LocalDate.of(year, month, day);}public String getName(){return name;}public double getSalary(){return salary;}public LocalDate getHireDay(){return hireDay;}public void raiseSalary(double byPercent){double raise = salary * byPercent / 100;salary += raise;}
}

 

 

 

 

数学函数

Math,StrictMath

枚举

enum{}

字符串String,null,不可修改,StringBuilder

charcharAt(int index)
Returns the char value at the specified index.
intcodePointAt(int index)
Returns the character (Unicode code point) at the specified index.
intcodePointBefore(int index)
Returns the character (Unicode code point) before the specified index.
intcodePointCount(int beginIndex, int endIndex)
Returns the number of Unicode code points in the specified text range of this String.
intcompareTo(String anotherString)
Compares two strings lexicographically.
intcompareToIgnoreCase(String str)
Compares two strings lexicographically, ignoring case differences.
Stringconcat(String str)
Concatenates the specified string to the end of this string.
booleancontains(CharSequence s)
Returns true if and only if this string contains the specified sequence of char values.
booleancontentEquals(CharSequence cs)
Compares this string to the specified CharSequence.
booleancontentEquals(StringBuffer sb)
Compares this string to the specified StringBuffer.
static StringcopyValueOf(char[] data)
Equivalent to valueOf(char[]).
static StringcopyValueOf(char[] data, int offset, int count)
Equivalent to valueOf(char[], int, int).
booleanendsWith(String suffix)
Tests if this string ends with the specified suffix.
booleanequals(Object anObject)
Compares this string to the specified object.
booleanequalsIgnoreCase(String anotherString)
Compares this String to another String, ignoring case considerations.
static Stringformat(Locale l, String format, Object... args)
Returns a formatted string using the specified locale, format string, and arguments.
static Stringformat(String format, Object... args)
Returns a formatted string using the specified format string and arguments.
byte[]getBytes()
Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
byte[]getBytes(Charset charset)
Encodes this String into a sequence of bytes using the given charset, storing the result into a new byte array.
voidgetBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin)
Deprecated. 
This method does not properly convert characters into bytes. As of JDK 1.1, the preferred way to do this is via the getBytes() method, which uses the platform's default charset.
byte[]getBytes(String charsetName)
Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.
voidgetChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Copies characters from this string into the destination character array.
inthashCode()
Returns a hash code for this string.
intindexOf(int ch)
Returns the index within this string of the first occurrence of the specified character.
intindexOf(int ch, int fromIndex)
Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
intindexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.
intindexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
Stringintern()
Returns a canonical representation for the string object.
booleanisEmpty()
Returns true if, and only if, length() is 0.
static Stringjoin(CharSequence delimiter, CharSequence... elements)
Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.
static Stringjoin(CharSequence delimiter, Iterable elements)
Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.
intlastIndexOf(int ch)
Returns the index within this string of the last occurrence of the specified character.
intlastIndexOf(int ch, int fromIndex)
Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.
intlastIndexOf(String str)
Returns the index within this string of the last occurrence of the specified substring.
intlastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.
intlength()
Returns the length of this string.
booleanmatches(String regex)
Tells whether or not this string matches the given regular expression.
intoffsetByCodePoints(int index, int codePointOffset)
Returns the index within this String that is offset from the given index by codePointOffset code points.
booleanregionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
Tests if two string regions are equal.
booleanregionMatches(int toffset, String other, int ooffset, int len)
Tests if two string regions are equal.
Stringreplace(char oldChar, char newChar)
Returns a string resulting from replacing all occurrences of oldChar in this string with newChar.
Stringreplace(CharSequence target, CharSequence replacement)
Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.
StringreplaceAll(String regex, String replacement)
Replaces each substring of this string that matches the given regular expression with the given replacement.
StringreplaceFirst(String regex, String replacement)
Replaces the first substring of this string that matches the given regular expression with the given replacement.
String[]split(String regex)
Splits this string around matches of the given regular expression.
String[]split(String regex, int limit)
Splits this string around matches of the given regular expression.
booleanstartsWith(String prefix)
Tests if this string starts with the specified prefix.
booleanstartsWith(String prefix, int toffset)
Tests if the substring of this string beginning at the specified index starts with the specified prefix.
CharSequencesubSequence(int beginIndex, int endIndex)
Returns a character sequence that is a subsequence of this sequence.
Stringsubstring(int beginIndex)
Returns a string that is a substring of this string.
Stringsubstring(int beginIndex, int endIndex)
Returns a string that is a substring of this string.
char[]toCharArray()
Converts this string to a new character array.
StringtoLowerCase()
Converts all of the characters in this String to lower case using the rules of the default locale.
StringtoLowerCase(Locale locale)
Converts all of the characters in this String to lower case using the rules of the given Locale.
StringtoString()
This object (which is already a string!) is itself returned.
StringtoUpperCase()
Converts all of the characters in this String to upper case using the rules of the default locale.
StringtoUpperCase(Locale locale)
Converts all of the characters in this String to upper case using the rules of the given Locale.
Stringtrim()
Returns a string whose value is this string, with any leading and trailing whitespace removed.
static StringvalueOf(boolean b)
Returns the string representation of the boolean argument.
static StringvalueOf(char c)
Returns the string representation of the char argument.
static StringvalueOf(char[] data)
Returns the string representation of the char array argument.
static StringvalueOf(char[] data, int offset, int count)
Returns the string representation of a specific subarray of the char array argument.
static StringvalueOf(double d)
Returns the string representation of the double argument.
static StringvalueOf(float f)
Returns the string representation of the float argument.
static StringvalueOf(int i)
Returns the string representation of the int argument.
static StringvalueOf(long l)
Returns the string representation of the long argument.
static StringvalueOf(Object obj)
Returns the string representation of the Object argument.

转载于:https://www.cnblogs.com/TheImportanceOfLiving/p/7337221.html

更多相关:

  • 上篇笔记中梳理了一把 resolver 和 balancer,这里顺着前面的流程走一遍入口的 ClientConn 对象。ClientConn// ClientConn represents a virtual connection to a conceptual endpoint, to // perform RPCs. // //...

  • 我的实验是基于PSPNet模型实现二维图像的语义分割,下面的代码直接从得到的h5文件开始往下做。。。 也不知道是自己的检索能力出现了问题还是咋回事,搜遍全网都没有可以直接拿来用的语义分割代码,东拼西凑,算是搞成功了。 实验平台:Windows、VS2015、Tensorflow1.8 api、Python3.6 具体的流程为:...

  • Path Tracing 懒得翻译了,相信搞图形学的人都能看得懂,2333 Path Tracing is a rendering algorithm similar to ray tracing in which rays are cast from a virtual camera and traced through a s...

  • configure_file( [COPYONLY] [ESCAPE_QUOTES] [@ONLY][NEWLINE_STYLE [UNIX|DOS|WIN32|LF|CRLF] ]) 我遇到的是 configure_file(config/config.in ${CMAKE_SOURCE_DIR}/...

  •     直接复制以下代码创建一个名为settings.xml的文件,放到C:UsersAdministrator.m2下即可