java课后作业一道关于统计字符串长度的题

题目:

Your are to output the length of a string. There are several test cases for each test group.

Input: Test case count T following by each test case. Example:
4
asdf
        
avc asd as
00100

Output:
4
8
10
5


我的解答:

  1. import java.util.Scanner;  
  2. public class Main {  
  3.     public static void main(String args[]) {  
  4.         Scanner s = new Scanner(System.in);  
  5.         int n = s.nextInt();  
  6.         s.nextLine();  
  7.         for(int i = 0; i < n; i++) {  
  8.             String str = s.nextLine();  
  9.             System.out.println(str.length());  
  10.         }  
  11.     }  
  12. }  

其他同学的解答:

  1. import java.util.Scanner;  
  2.   
  3. public class Main {  
  4.       
  5.     public static void main(String[] args){  
  6.         int count;  
  7.         Scanner in = new Scanner(System.in);  
  8.           
  9.         count = Integer.parseInt(in.nextLine());  
  10.           
  11.         for(int i=0; i<count; i++){  
  12.             String str = in.nextLine();  
  13.             System.out.println(str.length());  
  14.         }  
  15.           
  16.         in.close();  
  17.     }  
  18. }  


其中Integer.parseInt我没有见过,经过查阅资料,发现它是一个得到原始数据类型的一个特定的字符串


语法:

该方法有两种变型

static int parseInt(String s)

static int parseInt(String s,int radix)


参数:下面是参数的细节

String s:这是十进制的字符串表示形式

Int radix:这将用于将字符串转换为整数


返回值:

parseInt(String s):This returns an integer(decimal only).

parseInt(int i):This returns an integer,given a string representation of decimal,binary,octal,or hexadecimal(radix equals 10,2,8 or 16 respectively) numbers as input.


实例:

public class Test{ 
   public static void main(String args[]){
      int x =Integer.parseInt("9");
      double c = Double.parseDouble("5");
      int b = Integer.parseInt("444",16);
      System.out.println(x);
      System.out.println(c);
      System.out.println(b);
   }
}

这将输出以下结果:

9
5.0
1092
其中int b = Integer.parseInt("444",16);   是将444作为16进制数转换为10进制数


总之,这是一道很简单的题目,只要清楚string.length()函数就可以


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值