专业整理
知识分享
习题
2
3
.使用“
=
=
”对相同内容的字符串进行比
较,看会产生什么样的结果。
答:首先创建一个字符串变量有两种方式:
String str = new String("abc");
String str = "abc"
;
使用“
= =
”会因为创建的形式不同而产生
不同的结果:
String str1 = "abc";
String str2 = "abc";
System.out.println(str1=
=str2);
//true
String str1 = new String("abc");
String str2 = "abc";
System.out.println(str1=
=str2);
//false
String str1 = new String("abc");
String str2 = new String("abc");
System.out.println(str1=
=str2);
//false
因此自符串如果是对内容进行比较,使用
equals
方法比较可靠。
String str1 = "abc";
String str2 = "abc";
System.out.println(str1=
=str2);
//true
String str1 = new String("abc");
String str2 = "abc";
System.out.println(str1.equals(str2));
//true
String str1 = new String("abc");
String str2 = new String("abc");
System.out.println(str1.equals(str2));
//true
5
.编写一个程序,把变量
n
的初始值设置
为
1678
,
然后利用除法运算和取余运算把变
量的每位数字都提出来并打印,输出结果
为:
n=1678
。
n
的每位数字是
1
,
6
,
7
,
8
。
若
n
为任意值呢?
法一:
public class Exercise5{
public
static
void
main(String[]
args){
int n=1678;
int unit;
int decimal;
int hundred;
int thousand;
int count;
thousand=n/1000;
count=n%1000;
hundred=count/100;
count=count%100;
decimal=count/10;
count=count%10;
unit=count;
System.out.println("1678
包含的数
字分别是:
"+thousand+','+hundred+','+decimal+',
'+unit);
}
}
//
如果
n
为任意值
import java.io.*;
public class Exercise51{
public
static
void
main(String[]
args)
throws IOException{
System.out.print("
请
输
入
一
个
整
数:
");
InputStreamReader isStream=new
InputStreamReader(System.in);
BufferedReader bfReader=new
BufferedReader(isStream);
String
input=bfReader.readLine();
int length=input.length()-1;
int n=new