字符串的简单应用

1.简单类型和引用类型
Ineteger data1=new Ineteger(10);(自己定义的,在栈内存中开辟空间,data1存放新的变量10的地址;)
int data2=10;(data2存放数值10)
Ineteger data3=10;(在范围-128<data3<127之间均合法)
Ineteger data4=Integer.valueOf(10);
(1)装包
Ineteger data3=10;Integer.valueOf(10)
(2)拆包
int data2=data1;data1.intvalue return(10)
String str1 = “hello”;
String str2 = “hello”;
String str3 = new String(“hello”);
str1 == str2 true
str1 == str3 false
遍历字符串
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i); }

2.菜单
public static void main(String[] args) {
Scanner in=new.Scanner.(System.in);
System.out.println("------------");
System.out.println(“1.Register”);
System.out.println(“2.exit”);
System.out.println(“3…”);
int a = in.nextInt();
for(;? switch (a) {
case 1:
break;
case 2:
break;
case 3:
break;
}
}
3.找到字符串中的单词个数
public class WordsCalc {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.nextLine();
// true表示当前正在遍历一个单词,false表示当前遍历的已经不是一个单词了
boolean flag = true;
// 记录单词的个数
int number = 0;
// 用来记录遍历的字母的个数
int count = 0;
// 1. 循环整个字符串
for(int i=0; i<str.length(); ++i)
{
char ch = str.charAt(i);
//ch如果是字母,继续判断下一个;ch如果是其它字符,
// 不判断其它字符了,直接往后找空格

if(ch != ’ ') {
// 如果判断字符的过程中,遇见一个不是字母的字符,不用继续判断了
// 直接往后找

if(flag && !Character.isLetter(ch)){
// 已经不是一个字母了,也就是不是一个单词了
flag = false;
}
count++; // 当前字符是字母,统计字母个数
} else { // 遇见遇见空格了
if(flag){ // [i-count, i)
System.out.println(str.substring(i-count, i));//此处的str.substring(i-count, i)函数为从下标i-count到下标i
number++;
}
flag = true; // flag需要重置以下,马上要遍历下一个串了
count = 0; // 即将统计下一个单词,count重置一下
}
// 如果遇见空格了,我们需要检查一个状态,是刚遍历完了一个单词(数量+1),
// 还是没有判断字符,一直跑到空格处的

}
// 这里面需要处理一下长串中的最后一个小的字串是不是单词
if(flag){
System.out.println(str.substring(str.length()-count, str.length()));
number++;
}
System.out.println(number);
}
}
4.输出1000以内的完数
public static void main(String[] args) {
int[] arr = new int[500];
int idx = 0; // 记录数组元素的个数
for (int i = 1; i <= 1000; i++) {
int sum = 0;
for (int j = 1; j <= i/2; j++) {
if(i % j == 0){
arr[idx] = j;
idx++;
sum += j;
}
}
if(sum == i){
// 输出完数
System.out.print(i + " : ");
// 输出因子
for (int j = 0; j < idx; j++) {
System.out.print(arr[j] + " ");
}
System.out.println();
}
idx = 0; // indx重置,下来马上就开始保存下一个数字i的所有因子
}
}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值