使用 toString() 在 Java 中打印数组

Printing an array in Java with toString()

我试图在没有所有括号和逗号的情况下打印出我的数组,所以我试图覆盖 toString() 方法;但是我得到了 [I@5c647e05.抱歉,如果我的 post 格式不正确,这是我的第一个 post。我试图将数组显示为二进制数。我试过 toString() 但它包含方括号和逗号,我不能用它。

这是我的代码。

import java.util.Scanner;
import java.util.Arrays;
import java.io.*;
import java.util.*;

public class halfAdder {
    public static int[] binary = new int[2];

    public static void main(String[] args) {
        // Declaring booleans for the adder
        int sum = 0;
        int carry = 0;
        boolean a = false;
        boolean b = false;
        int tempA = 0;
        int tempB = 0;
        int notA = 0;
        int notB = 0;


        // Collecting all the information needed from the user
        Scanner console = new Scanner(System.in);

        System.out.print("Please enter your input for A: ");
        tempA = console.nextInt();
        System.out.print("Please enter an input for B: ");
        tempB = console.nextInt();


        // Deciding if what we collected as an input is either 0 or 1
        if(tempA == 0)
        {
            a = false;
            notA = 1;
            System.out.println("A hit first");
        }
        else
        {
            System.out.println("hit second");
            a = true;
            notA = 0;
        }

        if(tempB == 0)
        {
            System.out.println("B hit first");
            b = false;
            notB = 1;
        }
        else
        {
            System.out.println("B hit second");
            b = true;
            notB = 0;
        }

        sum = (notA*tempB)+(tempA*notB);

         if(tempA == 1 && tempB == 1)
        {
            carry = 1;
            sum = 0;
        } 

        binary[0] = carry;
        binary[1] = sum;


        System.out.println("a = " + tempA);
        System.out.println("b = " + tempB);
        System.out.println("not a = " + notA);
        System.out.println("not b = " + notB);
        System.out.println("Sum = " + sum);
        System.out.println("Carry = " + carry);
        System.out.println(binary.toString());
    }

    public String toString()
    {
        String binaryNumber = "The binary number is: ";

        for(int i = 0; i < binary.length; i++)
        {
            binaryNumber += binary[i];
        }
        return binaryNumber;
    }
}

如果您希望将数组转换为字符串,请使用 Arrays class:

String arrayAsString = Arrays.toString(binary);

有很多方法可以像二进制数一样显示数组的内容(没有上述方法添加的逗号和括号)。如果使用 Arrays.toString,则可以使用 String class 中提供的方法解析返回的 String。或者,您可以只使用 StringBuilder(或 String 添加)并循环遍历数组。

查看 Arrays.toString() 方法,用一行代码将数组输出为字符串。要删除逗号和括号,请使用 String.replace() 方法。