java新手:键盘录入以及运算符的使用

键盘录入

为了提高程序的灵活性,很多变量需要自己使用键盘录入。就需要使用Scanner,Scanner既可以接收基本类型,也可以接收字符串。
步骤:首先应该导入包,然后创建键盘录入对象,最后接收数据。
注意:可以先创建录入对象,然后使用快捷键Ctrl+Shift+o(字母不是零)导入包。

import java.util.Scanner;
public class scannerDemo {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);//创建键盘录入对象
		System.out.println("请输入一个数");
		int x = sc.nextInt();//接收数据
		System.out.println("x="+x);
		System.out.println("请输入一个字符串");
		String s = sc.nextLine();//接收字符串数据
		System.out.println("s:"+s);
	}
}

输出结果:

请输入一个数
12
x=12
请输入一个字符串
helloWorld
s:helloWorld
运算符的使用
  1. +:整数相加,直接数学相加; 字符参与加法运算,是拿字符在计算机中存储的数据值来参与运算; 字符串参与加法运算,是做字符串的拼接。
public static void main(String[] args) {
		int x=1;
		int y=5;
		char m='A';//'A'=65
		String n="hello";
		System.out.println(x+y);
		System.out.println(x+m);
		System.out.println(x+y+n);//先做x+y,在+n
		System.out.println(n+x+y);//先做n+x,在+y
	}

输出结果:

6
66
6hello
hello15

2.++和- -
在单独使用时,放前面和放后面结果是一样的。
在参与其他操作时,++在后,先拿变量的值做操作,然后变量加一,
++在前,先变量加一,再拿变量的值做操作。

public static void main(String[] args) {
		int x=1;
		int y=0;
		y = x++;
		System.out.println("y="+y);
		System.out.println("x="+x);
		x=1;
		y=++x;
		System.out.println("y="+y);
		System.out.println("x="+x);
	}

输出结果:

y=1
x=2
y=2
x=2
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值