主题:请问如何将含有空格的字符串输入到一个字符串中
daviswplc416
[专家分:0] 发布于 2008-04-12 22:26:00
System.out.print(UNCODED);
uncode = sc.next();
System.out.print(DELIMITERUSE);
delimiter = sc.next();
System.out.print(AMOUNT);
shift =sc.nextInt();
System.out.print(PUNCTUA);
punctuation = sc.nextBoolean();
当程序提示输入uncode字符的时候如果输入含有字符的字符串,“ad kad kkafd dk"程序会用空格分开将四个字符输入到四个变量中,而我只想将他们输入到第一个uncode中。不知道有没有朋友能帮我解决一下,想了一晚上了,也不知道怎么办。用sc.nextline()也不知道该怎么用,上网查了半天也没有头绪。哎
回复列表 (共14个回复)
11 楼
飞侠 [专家分:1380] 发布于 2008-04-13 20:42:00
for (int i = 0; i<strLength; i++)
{
//先得到一个字母
String getOneLetter=uncodeUpper.charAt(i)+"";
int num=0;
//如果是数字才能强制转换
if(isNumber(getOneLetter))
num=Integer.parseInt(getOneLetter);
if(num>=0 && num <= 9)
{
coded = coded + uncodeUpper.charAt(i);
}
else if((uncodeUpper.charAt(i) >= KNOWLEDGEA) && (uncodeUpper.charAt(i) <= KNOWLEDGEA + ALPHABET))
{
coded = coded + (char)((uncodeUpper.charAt(i) + shift)%91+ (uncodeUpper.charAt(i)+shift)/91*65);
}
else if(uncodeUpper.charAt(i) == ' ')
{
coded = coded + delimiter;
}
else if(punctuation)
{
coded = coded + uncodeUpper.charAt(i);
}
else
{
coded = coded;
}
}
System.out.println("The encoded string is:\"" + coded +"\"." );
//ask user whether to go for another test or not
System.out.println();
System.out.print("Try another?(y/n)");
//calculate user's choice to go for another test or not
ask = sc.next();
answer = ask.toLowerCase();
//empty the coded strings for the use nexttime
coded = "";
//store the numbers of strings encoded
number++;
}while (answer.equals(START));
//tell user how many times strings are encoded
System.out.println(number + " strings encoded");
}
}
12 楼
飞侠 [专家分:1380] 发布于 2008-04-13 20:43:00
/*问题1:我把Scanner sc = new Scanner (System.in);移到do...while中了就行了,并去掉第一个sc.nextLine()和其下第9行的sc.nextLine
().
问题2:你for循环后的第一个句子实际是没有被执行,需要先进行强制转换成int,才能判断是否在0-9间.我用了一个判断数字的方法然后在进行
强制转换了,因为只有数字才能强制转换成数字,不然会抛出
NumberFormatException
*/
13 楼
daviswplc416 [专家分:0] 发布于 2008-04-13 20:50:00
一个帖子只能给我50分,太感谢了
14 楼
飞侠 [专家分:1380] 发布于 2008-04-13 21:00:00
不谢,互相帮忙,呵呵
我来回复