A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 潘成旺 中级黑马   /  2015-3-6 22:02  /  1078 人查看  /  10 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 潘成旺 于 2015-3-6 22:05 编辑

代码如下:

/*                B:遍历字符串
                 
               
                分析:首先需要定义一个字符串;
                遍历,输出即可;
*/
package com.panchengwang;

public class LianXi2 {
        public static void main(String[] args) {
                String st = "helloworld";
                System.out.print("[");
                for(int x = 0;x < st.length();x++){
                        char ch = st.charAt(x);
                        if(ch == st.length()-1){
                                System.out.print(ch+"]");
                        }else{
                                System.out.print(ch+" ,");
                        }
                }
                System.out.println();
        }
}

我觉得代码是没问题的,嘿嘿,如有问题,请大婶赐教,小弟定虚心学习,可是问题是,我想要的输出结果是:[h,e,l,l,o,w,o,r,l,d]
可是真正输出的结果确是:[h ,e ,l ,l ,o ,w ,o ,r ,l ,d ,  这是为啥呀?

10 个回复

倒序浏览
if(ch == st.length()-1)
这句应该是 if(x == st.length()-1)
回复 使用道具 举报
将字符串转成字符数组在进行遍历
  1. package pack;
  2. class LianXi2 {
  3.         public static void main(String[] args) {
  4.                         String st = "helloworld";
  5.             char[] chs=st.toCharArray();
  6.                         System.out.print("[");
  7.                         for(int x=0; x<chs.length; x++){
  8.                                 if(x!=chs.length-1)
  9.                                         System.out.print(chs[x]+", ");
  10.                                 else
  11.                                         System.out.println(chs[x]+"]");
  12.                         }
  13.         }
  14. }
复制代码
回复 使用道具 举报
(ch == st.length()-1) 这一句改成(x==st.length-1)
回复 使用道具 举报
遍历字符串,学习了。。。
回复 使用道具 举报
同意楼上观点
回复 使用道具 举报
想要在最后打印 [ 应该对x进行判断,是不是遍历完了字符串
你的判断语句虽然没有语法错误,但是用字符串中字符的ASCI码和字符串的长度进行比较,返回的是false
所以,你要输出的语句,永远执行不到
程序:
public class test1 {
    public static void main(String[] args) {
            String st = "helloworld";
            System.out.print("[");
            for(int x = 0;x < st.length();x++){
                    char ch = st.charAt(x);
                    if(x == st.length()-1){
                            System.out.print(ch+"]");
                 
                    }else{
                            System.out.print(ch+" ,");
                    }
            }
            System.out.println();
    }
}
回复 使用道具 举报
进来学习学习~~
回复 使用道具 举报
yangruijing 发表于 2015-3-7 12:33
想要在最后打印 [ 应该对x进行判断,是不是遍历完了字符串
你的判断语句虽然没有语法错误,但是用字符串中 ...

哦 这样啊,谢谢了
回复 使用道具 举报
嗯 说的都是正解,把ch==st.length()-1,改成x==st.length()-1.
回复 使用道具 举报
艺多不压身丶 发表于 2015-3-6 22:49
将字符串转成字符数组在进行遍历

谢谢,终于懂了
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马