快捷输入方式 :输入main后按Alt + /
public static void main(String[] args) { }输出函数:System.out.print();
System.out.println("");可以省略输出内容后面的n,自带换行功能。
+号代表连接各个字符
System.out.println("Hello world!"); System.out.println("a = "+a); System.out.println("a = "+a + " b = "+b + " c = "+c);
测试用例:
出现小数点,Java默认为double类型,如果需要定义为float类型必须使用强制转换float f = (float)0.1;
public class Test { public static void main(String[] args) { System.out.println("Hello world!"); System.out.println("hello2"); int a; a = 10; int b; b = 20; System.out.println("a = "+a); System.out.println("b = "+b); int c = a+b; System.out.println("a = "+a + " b = "+b + " c = "+c); System.out.println(a + "+" + b + "=" + c); float f = (float)0.1; double d = 0.2; System.out.println("f = "+f); System.out.println("d = "+d); } }
运行结果
a = 10 b = 20 a = 10 b = 20 c = 30 10+20=30 f = 0.1 d = 0.2数组
Java定义数组的三种方式
int a[] = {1,2,3}; int array[] = new int[3]; int array[] = null; array = new int[3];
测试用例
public class Test { public static void main(String[] args) { int a[] = {1,2,3};//第一种定义方式,与C语言一样 System.out.println(a[0]); System.out.println(a[1]); System.out.println(a[2]); //int array[] = new int[3];//第二种定义方式,等于C语言的int array[3]; int array[] = null; array = new int[3];//第三种定义方式 int i; for(i=0;i运行结果
1 2 3 0 1 2定义数组推荐使用的写法
int[] testArray = new int[3]; int[] score = {1,2,3,4,5,6,7,8,9,10};函数Java的函数调用,函数名定义前前需要加 static ,其它和C语言一样定义调用。
public class Test { static void myprintf(){ System.out.println("Hello World!"); } static void putAint(int a){ System.out.println("输出一个数字:"+a); } public static void main(String[] args) { myprintf(); putAint(10); } }Hello World! 输出一个数字:10输入Scanner sc = new Scanner(System.in);需要初始化,输入后提示“不认识”时可以按快捷键ctrl+shift+o导包后可以使用。
import java.util.Scanner; public class Test { public static void main(String[] args) { Scanner sc = new Scanner(System.in);//ctrl+shift+o导包 int a; String str; float f; double d; System.out.println("请输入一个数字:"); a = sc.nextInt(); System.out.println("请输入一个字符串:"); str = sc.nextLine();//多写一次吸收回车键 str = sc.nextLine(); System.out.println("请输入一个float数字:"); f = sc.nextFloat(); System.out.println("请输入一个double数字:"); d = sc.nextDouble(); System.out.println("a = "+a); System.out.println("str = "+str); System.out.println("f = "+f); System.out.println("d = "+d); } }运行结果
请输入一个数字: 5 请输入一个字符串: char 请输入一个float数字: 5.6 请输入一个double数字: 6.33 a = 5 str = char f = 5.6 d = 6.33欢迎分享,转载请注明来源:内存溢出
评论列表(0条)