英文:
String.replace() is removing parts of my string i didn't tell it to
问题
//calculate price of text and add values
textCrop = text.replaceAll(" ", ""); //heres where I'm trying to remove whitespaces
System.out.println(textCrop);
textPrice = ((text.length() + 1) * 1.45);
finalPrice = textPrice + sizePrice;
System.out.print("$");
英文:
I have a program that is calculating the value of a sign based on the square footage and a fee per character. I need to remove the whitespaces to accurately count the number of characters, but is using .replace and .replaceAll, i have found that when i print the resulting string, everything after the first whitespace is removed. For example, if I entered "Welcome to java" when user is prompted to assign a value to the String variable, text, textCrop would simply print "Welcome" after the text.replaceAll line runs. What am I doing wrong?
//calculate price of text and add values
textCrop = text.replaceAll(" ", ""); //heres where I'm trying to remove whitespaces
System.out.println(textCrop);
textPrice = ((text.length() + 1) * 1.45);
finalPrice = textPrice + sizePrice;
System.out.print("$");
答案1
得分: 0
以下是您的代码翻译部分:
这是我的代码,对我来说完美地运行了。您需要阅读整行。
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String text = sc.nextLine();
String textCrop = text.replaceAll(" ", ""); //这里是我尝试去除空格的地方
System.out.println(textCrop);
double textPrice = ((text.length() + 1) * 1.45);
double finalPrice = textPrice ;
System.out.print("$");
}
}
英文:
This was my code and it worked perfectly for me. You need to read the entire line.
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String text = sc.nextLine();
String textCrop = text.replaceAll(" ", ""); //heres where I'm trying to remove whitespaces
System.out.println(textCrop);
double textPrice = ((text.length() + 1) * 1.45);
double finalPrice = textPrice ;
System.out.print("$");
}
}
答案2
得分: 0
你在读取输入时应该使用Scanner.nextLine()
。
为了准确地计算不包含空格的字符数,你应该找到 textCrop 的长度,而不是 text。textCrop.length()
。
英文:
You should use Scanner.nextLine()
when reading the input.
To accurately count the number of characters without white spaces, you should find the length of the textCrop and not text. textCrop.length()
专注分享java语言的经验与见解,让所有开发者获益!
评论