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

时间:2015-04-20 21:55:10

标签: java arrays string tostring

我试图在没有所有括号和逗号的情况下打印出我的数组,所以我试图覆盖toString()方法;但是我得到了[I @ 5c647e05的输出。对不起,如果我的帖子表格不好,这是我的第一篇帖子。我试图将数组显示为二进制数。我尝试了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;
    }
}

2 个答案:

答案 0 :(得分:1)

如果您希望将数组转换为String,请使用Arrays类:

String arrayAsString = Arrays.toString(binary);

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

答案 1 :(得分:0)

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

相关问题