.parseBoolean将字符串为”true”的情况解析为”false”?

huangapple go评论85阅读模式
英文:

.parseBoolean turns out "false" with the String being "true"?

问题

import java.io.FileReader;
import java.io.IOException;

public class StackOverflow {

	public static void main(String[] args) throws IOException {
		String textRead = "";
		FileReader fileReader = new FileReader("test.txt");
		char[] Array = new char[100];
		fileReader.read(Array);
		
		for(int i = 0; i<Array.length; i++) 
		{
			//if I were to print textRead it would print true
			textRead = textRead + Array[i];
		}
		//The .txt file contains only "true" and nothing else
		boolean test = Boolean.parseBoolean(textRead);
		//This prints out false for some reason
		System.out.print(test);
		
		fileReader.close();

	}

}

但当我运行此程序时,它打印出值 "false",即使应该读取的 .txt 文件只包含 "true"。

我尝试寻找解决方案,但由于我对Java和编程都还很陌生,所以没有取得多大进展,有人可以帮我解决这个问题吗?

英文:

So I was trying to make a program that reads the content of a .txt file and then stores it as a boolean

import java.io.FileReader;
import java.io.IOException;

public class StackOverflow {

	public static void main(String[] args) throws IOException {
		String textRead = &quot;&quot;;
		FileReader fileReader = new FileReader(&quot;test.txt&quot;);
		char[] Array = new char[100];
		fileReader.read(Array);
		
		for(int i = 0; i&lt;Array.length; i++) 
		{
			//if I were to print textRead it would print true
			textRead = textRead + Array[i];
		}
		//The .txt file contains only &quot;true&quot; and nothing else
		boolean test = Boolean.parseBoolean(textRead);
		//This prints out false for some reason
		System.out.print(test);
		
		fileReader.close();

	}

}

But when I run this it prints out the value "false" even though the .txt that was supposed to be read only contained "true".

I tried looking for a solution but didn't get very far as I am still pretty new to java and coding in general, can anyone help me out with this?

答案1

得分: 1

这实际上是您的String内容,没有修剪:

00000000: 7472 7565 0a00 0000 0000 0000 0000 0000  true............
00000010: 0000 0000 0000 0000 0000 0000 0000 0000  ................
00000020: 0000 0000 0000 0000 0000 0000 0000 0000  ................
00000030: 0000 0000 0000 0000 0000 0000 0000 0000  ................
00000040: 0000 0000 0000 0000 0000 0000 0000 0000  ................
00000050: 0000 0000 0000 0000 0000 0000 0000 0000  ................
00000060: 0000 0000                                ....

与C/C++等语言不同,Java的String 可以 包含空字符。因此,您需要在读取后使用 textRead = textRead.trim(); 进行修剪,但正如我所说,最好是按行读取。尽管如此,无论如何读取,调用 trim() 是明智的 .parseBoolean将字符串为”true”的情况解析为”false”?

英文:

This is, in fact the content of your String without trimming:

00000000: 7472 7565 0a00 0000 0000 0000 0000 0000  true............
00000010: 0000 0000 0000 0000 0000 0000 0000 0000  ................
00000020: 0000 0000 0000 0000 0000 0000 0000 0000  ................
00000030: 0000 0000 0000 0000 0000 0000 0000 0000  ................
00000040: 0000 0000 0000 0000 0000 0000 0000 0000  ................
00000050: 0000 0000 0000 0000 0000 0000 0000 0000  ................
00000060: 0000 0000                                ....

Unlike languages like C/C++, Java Strings can contain null characters. So you need textRead = textRead.trim(); after reading, but as I said, it would be better to read lines. Having said that, however you read it, it would be wise to call trim() .parseBoolean将字符串为”true”的情况解析为”false”?

答案2

得分: 1

以下是翻译好的部分:

char 数组被创建时,它最初会包含空字符值。

char[] Array = new char[100];

因此,当您循环遍历 Array 时,textRead 将会附加空的 char 值。

textRead = textRead + Array[i];

您可以通过在 for 循环 内部添加一个检查来避免这种情况。

for(int i = 0; i&lt;Array.length; i++)
{
    if (Array[i] == '\u0000') break;

    //如果我打印textRead,它将会打印true
    textRead = textRead + Array[i];
}

或者,您可以利用 String 构造方法,或者使用 String#valueOf 方法来构造字符串。随后,使用 String#trim 方法来移除任何前导和尾随的空白字符,包括空字符。

textRead = new String(Array).trim();
textRead = String.valueOf(Array).trim();

值得注意的是,您可以利用 BufferedReader 类,该类具有 readLine 方法。

BufferedReader fileReader = new BufferedReader(new FileReader("test.txt"));
textRead = fileReader.readLine();
fileReader.close();
英文:

When the char array is created it will initially contain null character values.

char[] Array = new char[100];

So, when you are looping though Array, textRead will have null char values appended to it.

textRead = textRead + Array[i];

You can avoid this by adding a check within the for-loop.

for(int i = 0; i&lt;Array.length; i++)
{
    if (Array[i] == &#39;\u0000&#39;) break;

    //if I were to print textRead it would print true
    textRead = textRead + Array[i];
}

Alternately, you can utilize the String constructor method, or the String#valueOf method, to construct the string.
Subsequently, use the String#trim method to remove any leading and trailing white-space characters&mdash;which includes the null character.

textRead = new String(Array).trim();
textRead = String.valueOf(Array).trim();

It's worth noting, you can utilize the BufferedReader class, which has a readLine method.

BufferedReader fileReader = new BufferedReader(new FileReader(&quot;test.txt&quot;));
textRead = fileReader.readLine();
fileReader.close();

答案3

得分: 0

public static boolean parseBoolean(String s) { return "true".equalsIgnoreCase(s); }

Hope that explains your issue.
Also the unused elements in your char array are treated as nulls

英文:

public static boolean parseBoolean(String s) {
return &quot;true&quot;.equalsIgnoreCase(s);
}

Hope that explains your issue.
Also the unused elements in your char array are treated as nulls

答案4

得分: 0

你已经被解释过(非常好地)随意声明一个数组来存储值的问题,其中您可能不知道需要读取整个布尔值文件的元素数量,因此我不会在这里再次这样做。然而,我建议您根本不使用数组,而是使用List接口ArrayList来存储文件行结果,这些结果可以动态增长,并且不会可能充满null元素(如果您不希望如此)。

下面是如何使用List接口的示例。请务必阅读代码中的注释。

应该注意,在这个用例中,文件行被修剪以去掉空格等。您还会注意到使用String#matches()方法与正则表达式(regex)字符串来验证读取的文件行是否包含“true”或“false”。下面是对使用的正则表达式的简要解释:

  • (?i) 忽略大小写;
  • true 文件行仅包含“true”;
  • |
  • false 文件行仅包含“false”;

再次阅读代码中的注释:

// 用于存储true/false文件行结果的List接口:
List<Boolean> list = new ArrayList<>();

/* 在这里使用`Try With Resources`自动关闭()读取器
   并在完成时释放资源。 */
try (Scanner reader = new Scanner(new File("test.txt"))) {
    String line;
    while (reader.hasNextLine()) {
        line = reader.nextLine().trim();
        /* 任何包含除true或false之外的内容的文件行都会被忽略,包括空行。 */
        // 行是否为true或false(不区分大小写):
        if (line.matches("(?i)true|false")) {
            // 将行转换为布尔值并添加到List中:
            list.add(Boolean.valueOf(line));
        }
    }

    // 如果您愿意,可以将列表转换为数组(在读取之后):
    // Boolean[] array = list.toArray(new Boolean[0]);
        
    // 显示List:
    for (Boolean bool : list) {
        System.out.println(bool);
    }
}
catch (FileNotFoundException ex) {
    System.err.println(ex.getMessage());
}

(Note: The code comments and URLs are retained as provided.)

英文:

You've already been explained (quite nicely) the problem with arbitrarily declaring an array to hold values where you possibly have no idea how many elements you may need to read the entire file of boolean values so I won't do that again here. I will suggest however, that you don't use an array at all but instead, use a List Interface or an ArrayList to hold file line results which can grow dynamically and wont possibly end up being full of null or empty elements (if you don't want it to).

Below is an example of how a List Interface can be used. Be sure to read the comments in code.

It should be noted that, in this use case, the file lines are trimmed of white-spacing etc as the file lines are read. You will also note that the String#matches() method is used with a Regular Expression (regex) string to validate the fact that a read file line contains either "true" or "false". Below is a brief explanation of the regex used:

  • (?i) Ignore letter case;
  • true The file line contains only "true";
  • | OR
  • false The file line contains only "false";

Again...read the comments in code:

// List Interface to hold true/false file line results:
List&lt;Boolean&gt; list = new ArrayList&lt;&gt;();
    
/* `Try With Resources` used here to auto-close() the reader
   and free resources when done.        */
try (Scanner reader = new Scanner(new File(&quot;test.txt&quot;))) {
    String line;
    while (reader.hasNextLine()) {
        line = reader.nextLine().trim();
        /* Any file line that contains anything other than
           true or false is ignored, including blank lines. */
        // Is the line true or false (not letter case sensitive):
        if (line.matches(&quot;(?i)true|false&quot;)) {
            // Convert line to boolean and add to List:
            list.add(Boolean.valueOf(line));
        }
    }

    // Convert list to an array if you like (after the reading):
    // Boolean[] array = list.toArray(new Boolean[0]);
        
    // Display List:
    for (Boolean bool : list) {
        System.out.println(bool);
    }
}
catch (FileNotFoundException ex) {
    System.err.println(ex.getMessage());
}

huangapple
  • 本文由 发表于 2023年6月22日 01:47:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76525934.html
匿名

发表评论

匿名网友

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

确定