ART
ART

Reputation: 7

Set int to a blank in array

i want to set my array to print out a blank space when it meets its condition in an IF statement. This array is a int data type. When i type:

item2[2] = ' '; 

it comes up as 32 when i print it.

Any solutions?

Upvotes: 0

Views: 3495

Answers (5)

Peter Lawrey
Peter Lawrey

Reputation: 533492

If you want to store char in an array, why not use a char[]

char[] item2 = new char[10];
item2[2] = ' '; 
System.out.println('|' + items2[2]+'|');

prints

| |

Upvotes: 0

anizzomc
anizzomc

Reputation: 252

The character ' ' has that value 32 on int, you need to diference when put a blank or not. If your space of values is for example only positive values, you can save a -1 where do you what a space and your code could be something like this:

for(int i:item2){
  if(i == -1) {
    //Print a blank
  } else {
    //Print the number
  }
}

Or you can do a better way, instead of using int, use an array of class Integer, autoboxing will do the automatic convertion and use null as "blank value"

Upvotes: 1

Brian Roach
Brian Roach

Reputation: 76898

It's an int array. It can only hold integers.

32 is the ASCII value for space, and that's what's being stored when you say item2[2] = ' ';.

Upvotes: 3

Jigar Joshi
Jigar Joshi

Reputation: 240880

No. as your data type is int it will print int representation.

if you cast to (char) then it might mess up with actual number to char which isn't needed,

and it is coming 32 because ascii value of ' ' is 32

Better to go for array of String it will hold both number as well as space . and process them accordingly

Upvotes: 5

Gaurav
Gaurav

Reputation: 28755

Ascii value of ' ' (space) is 32 in html, thats why it is echoing 32.

So the char ' ' will be converted to int, which is 32

Upvotes: 2

Related Questions