[英]My Java program for removing special characters and white space from user input of name fails when I test it with spaces
我是一名学生,正在做一项让我们尝试一些我们没有涵盖的技术的任务。 从用户输入中删除特殊字符和空格,我想出了如何删除特殊字符,但是当我尝试我的程序时在我的名字中插入一个空格时,我的名字返回给我,缺少空格后面的任何字母。 就像,“Pat ricia”变成了“Pat”。 我不得不采用一种不同的技术来删除特殊字符,因为“replaceAll”在那里对我不起作用,而且在删除空格方面对我不起作用。 我可以用另一双眼睛告诉我我错过了什么吗?
package edu.gmc.Course_Project;
import java.util.Scanner;
public class Input_Name {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//asking for user input
System.out.print("enter your name: ");
String name = scan.next();
//Java won't do all this at once (2 step process) so I'm converting the whole name to lower case first
name=name.toLowerCase();
//now to get the first character
char first=name.charAt(0);
//and changing it to upper case
first=Character.toUpperCase(first);
String newName="";
newName+=first;
//I'm not really sure about this part, but it has to do with the length...without it, my name was returned to me as "P"
for(int i=1;i<name.length();i++)
{
//this part ignores anything other than A-Z or a-z...I had a different method earlier but I couldn't get it to work properly
char ch=name.charAt(i);
if(ch>='a' && ch<='z')
{
newName+=ch;
}
}
//removing white spaces
newName = newName.replaceAll("\\s+", "");
//the program is complete, now what does it do?
System.out.println("your name is "+newName);
}
}
您的程序无法运行的原因是因为您使用的是
String name = scan.next();<\/code>
在程序的最开始,此命令将存储输入的下一个字符串,并且由于有一个空格,它只是存储空格之前的第一个字符串,而不是您需要使用
String name = scan.nextLine();<\/code>
因为它将存储整行,包括空格和其他字符串,
"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.