JAVA初学程序
1.
//比较输入的三个数值的大小
package first_java;
import java.util.Scanner;
public class Practice_1 {
public static void main(String[] args){
System.out.println(“请输入三个数”);
Scanner num = new Scanner(System.in);
int a = num.nextInt(); //定义三个输入的值
int b = num.nextInt();
int c = num.nextInt();
int max = 0; // 定义最大值max并初始化
if(a>=b&&a>=c){ //逻辑比较值的大小
max=a;
}else if(b>=a&&b>=c){
max=b;
}else if(c>=a&&c>=b){
max =b;
}else{
System.out.println(“无法比较”); //输入的数值无法比较,例如:特殊符号
}
System.out.println(“max=”+max); //输出最大值max
}
}
2.
package third_java;
public class String_equals {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s1="hello"; //创建s1
String s2=new String("Hello");//创建对象s2
System.out.println(s1==s2);//比较s1和s2若用"=="则比较的是存放的内存地址
//通过debug可以发现s1的id=33;而s2的id=37;故为false.
//若想比较字符串的内容是否相等,应该使用equals.
//equals的含义就是比较两个字符串的内容是否相同;如下:
System.out.println(s1.equals(s2)); //结果为true,该类型是区分大小写的,注意代码的大小写
//若想不区分大小写,可用equalsIgnoreCase;代码如下:
System.out.println(s1.equalsIgnoreCase(s2));//结果为true
//equalsIgnoreCase的含义:比较字符串内容,忽略大小写.
//注意:忽略大小写指的是字符串内容的大小写,并非是对象s1,s2中s的大小写.
}
}
3.
//该程序是练习String类中的contains;
//contains的中文翻译是:包含;n.容纳; v.包含,某字符串;
//contains在JAVA中的含义:判断字符串中农是否包含某个子字符串.
//contains返回的是布尔类型true 和false,包含的话就返回true,不包含的话就返回false
package third_java;
public class Contains {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s1 = “Hello”; //??
String s2 = new String(“Hello”);// 创建新对象s2
System.out.println(s1.contains(“ew”)); // 结果为false.判断s1中是否含有 ew.
System.out.println(s1.contains(“he”)); // 结果为false.判断是否区分大小写,显而是区分大小写的.
System.out.println(s1.contains(“Helo”)); // 结果为false.判断是否区分相隔的子字符串.
System.out.println(s1.contains(“He”)); // 结果为true
System.out.println(s1.contains(“Hello”));// 可以包含等于或小于其本身字符串的内容(紧挨着的字符串).
}
}
4.
/*该程序使用了String类中的trim、length、charAt方法
中文解释:
trim:n.修剪;vt.修剪;
length:长度
charAt:截取一个字符
JAVA中的释义:
trim:去除开头和结尾的一个或多个空格
length:获取长度
charAt:获取指定索引位置的某个字符(只能获得单个字符)
*/
package third_java;
public class MyTrim {
public static void main(String[] args) {
// TODO Auto-generated method stub
String a1 = " *hello world * ";
System.out.println(a1.trim());//输出为:*hello world * --只消除了第一个*之前喝最后一个*之后的空格
System.out.println(a1.length());//结果:25. 在双引号内的文字、空格、特殊符号都占一个长度.
System.out.println(a1.charAt(5));/*结果:l(字母"l",非数字1)获得字符串的第五个字符(该方法忽略了空格,但不忽略特殊符号).*/
}
}
5.
//该代码的意图是输出遍历字符串的每一个字符
package homework7_27;
public class Traverse_Everyone {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s1 ="Hello world!";//定义一个字符串
//利用循环开始遍历字符串
for(int i=0;i<s1.length();i++){
/*System.out.println(s1.charAt(i));//输出遍历的字符
/ /输出结果H
* e
l
l
o
w
o
r
l
d
!*/
System.out.print(i+":"+s1.charAt(i)+"\t");
//输出 0:H 1:e 2:l 3:l 4:o 5: 6:w 7:o 8:r 9:l 10:d 11:!
//这样的输出更容易读取遍历的字符
}
}
}