开发者

Print to console using System.out.write

开发者 https://www.devze.com 2023-01-24 14:50 出处:网络
It is homework question. Question: \"Use an array of integers with size 10 and print the content of the array using write( ) method.

It is homework question.

Question:

"Use an array of integers with size 10 and print the content of the array using write( ) method.

Note: Please do not use System.out.println( ) method."

This is what I have tried so far, but it doesn't work.

int i = 0;
while (i != array.length) {
  byte[] temp = new byte[4];
  temp[0] = (byte) (array[i] & 256);
  array[i] = array[i] >> 8;
  temp[1] = (byte) (array[i] & 256);
  array[i] = array[i] >> 8;
  temp[2] = (byte) (array[i] & 256);
  array[i] = array[i] >> 8;
  temp[3] = (byte) (array[i] & 256);
  System.out.write(开发者_JAVA百科temp, 0, 4);
  i++;
}

I can't find a way to do this, please help me out.

Thanks in advance. :)


void printInt(int x) {
  String s = String.valueOf(x);
  for(int i = 0; i < s.length(); i++) {
     System.out.write(s.charAt(i));
  }
  System.out.write('\n');
}

Edit: prettier:

void printInt(int x) {
  String s = String.valueOf(x);
  System.out.write(s.getBytes());
  System.out.write('\n')
}


Why are you making an array of bytes ? There is a write(int b) method.

Integer array = new Integer[10];
// populate array with some integers
for (Integer i : array) {
    System.out.write((int)i);
}

even the cast (int)i isnt necessary as autoboxing will take care of that.


The trick is to convert each digit of the int into a char. and then write the char using System.out.write.
So for example, if one of the int values is 91. You'll need to do
System.out.write('9');
System.out.write('1');
System.out.flush();


Have an integer array of size 10, i.e. int[] i = new int[10] and write each of them in System.out.write(int b) where the write() method accept an integer as parameter.


This is really ugly but it worked....

/**
 * 
 */
package testcases;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * @author The Elite Gentleman
 *
 */
public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] array = {10, 20, 30, 40, 50};

        StringBuffer sb = new StringBuffer();
        for (int i: array) {
            sb.append(String.valueOf(i));
        }

        try {
            System.out.write(sb.toString().getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号