`String.replace()`正在移除我没有告诉它要移除的字符串部分。

huangapple 未分类评论47阅读模式
英文:

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 的长度,而不是 texttextCrop.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()

huangapple
  • 本文由 发表于 2020年6月29日 08:13:05
  • 转载请务必保留本文链接:https://java.coder-hub.com/62629545.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定