11

It appears there is no easy way of doing this, but this is what i've done so far and if someone could correct it to make it work that would be great. At "newarray [e] = array [i].intValue ();" i get an error "No method named "intValue" was found in type "java.lang.Object"." Help!

/*
Description: A game that displays digits 0-9 and asks the user for a number N.
 It then reverses the first N numbers of the sequence. It continues this until
 all of the numbers are in order.
 numbers

*/

import hsa.Console;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Arrays;


public class ReversalGame3test

{
    static Console c;

    public static void main (String[] args)
{
    c = new Console ();

    c.println ("3. REVERSAL GAME");
    c.println ("");
    c.println ("Displayed below are the digits 0-9 in random order. You must then enter a");
    c.println ("number N after which the computer will reverse the first N numbers in the");
    c.println ("sequence. The goal of this game is to sort all of the numbers in the fewest");
    c.println ("number of reversals.");
    c.println (""); //introduction

    List numbers = new ArrayList ();
    numbers.add ("0");
    numbers.add ("1");
    numbers.add ("2");
    numbers.add ("3");
    numbers.add ("4");
    numbers.add ("5");
    numbers.add ("6");
    numbers.add ("7");
    numbers.add ("8");
    numbers.add ("9");
    Collections.shuffle (numbers);
    Object[] array = numbers.toArray (new String [10]); // declares + shuffles numbers and converts them to array

    c.print ("Random Order: ");
    for (int i = 0 ; i < 10 ; i++)
    {
        c.print ((array [i]) + " ");
    }
    c.println ("");

    boolean check = false;
    boolean check2 = false;
    String NS;
    int N = 0;
    int count = 0;
    int e = -1;
    int[] newarray = new int [10];

    //INPUT
    do
    {
        c.print ("Enter a number: ");
        NS = c.readString ();
        count += 1;

        check = isInteger (NS);
        if (check == true)
        {
            N = Integer.parseInt (NS);
            if (N < 1 || N > 10)
            {
                check = false;
                c.println ("ERROR - INPUT NOT VALID");
                c.println ("");
            }
            else
            {
                c.print ("Next Order: ");
                for (int i = N - 1 ; i > -1 ; i--)
                {
                    e += 1;
                    newarray [e] = array [i].intValue ();
                    c.print ((newarray [e]) + " ");
                }
                for (int i = N ; i < 10 ; i++)
                {
                    e += 1;
                    newarray [e] = array [i].intValue ();
                    c.print ((newarray [e]) + " ");
                }
                check2 = sorted (newarray);
            } // rearranges numbers if valid
        } // checks if N is valid number
    }
    while (check == false);
} // main method


public static boolean isInteger (String input)
{
    try
    {
        Integer.parseInt (input);
        return true;
    }
    catch (NumberFormatException nfe)
    {
        return false;
    }
} //isInteger method


public static boolean sorted (int array[])
{
    boolean isSorted = false;

    for (int i = 0 ; i < 10 ; i++)
    {
        if (array [i] < array [i + 1])
        {
            isSorted = true;
        }
        else if (array [i] > array [i + 1])
        {
            isSorted = true;
        }
        else
            isSorted = false;

        if (isSorted != true)
            return isSorted;
    }
    return isSorted;
} // sorted method

}

4
  • 1
    Why do you create an array of Object in the first place? Commented Jan 16, 2013 at 3:23
  • because i had no choice, it wouldn't let me convert the ArrayList to an int array directly. Commented Jan 16, 2013 at 21:48
  • You could use an array of Integer. Commented Jan 16, 2013 at 23:23
  • but I still cannot compare an Integer array like I would an int one, and if so I don't know how to Commented Jan 17, 2013 at 5:09

6 Answers 6

11

You can use Integer.valueOf.

Integer.valueOf((String) array [i])

The Integer class has a method valueOf which takes a string as the value and returns a int value, you can use this. It will throw an NumberFormatException if the string passed to it is not a valid integer value.

Also If you are using java5 or higher you can try using generics to make the code more readable.

6
  • I'm questioning the efficiency of this solution (not as if it matters significantly in this case). Is there a benefit to casting (String) then using Integer.valueOf() over (Integer) then intValue() that I'm just not seeing? Commented Jan 16, 2013 at 3:35
  • The problem is array is not an Interger[] it is an Object[] containing String values so (Integer)array[i] should throw an class cast exception. Commented Jan 16, 2013 at 3:38
  • Just tested that, no exception thrown here. Statement ((Integer)x[1]).intValue() returns the appropriate value where x is an array of type Object[] and x[1] is not null. Commented Jan 16, 2013 at 3:42
  • Can you check again because it just give me java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer error on line newarray[e] = ((Integer)array[i]).intValue();. If you see the code array contains String values, java will not allow you to cast a String value to a Integer value, again it is not a compile time error it is a runtime exception, so you need to execute the code to get the exception Commented Jan 16, 2013 at 3:47
  • Oh, that makes more sense. I was operating under the assumption that the values were stored as type int, not type String, because storing as String would be generally silly for something like this. I see the error now. Commented Jan 16, 2013 at 3:51
5

You can implement the same using Generics, which would be easier.

List<Integer> numbers = new ArrayList<Integer> ();
Integer[] array = numbers.toArray (new Integer [10]);
3
  • Anytime I try to use any code with "< >" I get 'invalid assignment operator'. Do you know why/how to fix? Commented Jan 16, 2013 at 21:12
  • Are you using java5 or higher version... Generics is supported only from java5... Commented Jan 17, 2013 at 0:55
  • I suppose not then, I'm using something called "Ready to Program" for java Commented Jan 17, 2013 at 5:10
3

have a try commons-lang

org.apache.commons.lang.ArrayUtils.toPrimitive(Integer[])
1
  • I have no idea how to go about doing whatever that means. Sorry, I have an awful comp.sci. teacher. Commented Jan 16, 2013 at 21:19
2

You can't call .intValue() on an Object, as the Object class lacks the method intValue().

Instead, you need to cast the Object to the Integer class first, like so:

newarray[e] = ((Integer)array[i]).intValue();

Edit: Just a helpful tip on StackOverflow - please limit your code to what's relevant! Though sometimes large blocks of code are necessary, in this case, it was not. It makes the question look nicer, and it's bound to get better responses that way.

Also, please do not use the tag. It is currently deprecated and is in the process of burnination.

1
  • Thanks, I just wanted the answers to be most accurate since I`ve searched on this site for hours for a solution and have found nothing. I tried your suggestion and it said java.lang.ClassCastException at that line... Commented Jan 16, 2013 at 15:29
1

I know this is pretty late, but here are my 2 cents!!

int[] newArray=new int[objectArray.length];
Object[] objectArray = {1,2,3,4,5};

for(int i=0;i<objectArray.length();i++){
    b[i]=(int)objectArray[i];
}
0
0

Assuming that user needs to convert Object[] to Integer[].

Simply use Arrays.copyOf. Full documentation here.

Object [] temp = {1,2,3,4,5};
Integer[] result = Arrays.copyOf(temp, temp.length, Integer[].class);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.