简体   繁体   English

将 Object[] 数组转换为 java 中的 int [] 数组?

[英]Converting a Object[] array to an int [] array in java?

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 ();"在“newarray [e] = array [i].intValue();”处i get an error "No method named "intValue" was found in type "java.lang.Object"."我收到错误消息“在类型“java.lang.Object”中找不到名为“intValue”的方法。” 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

} }

You can use Integer.valueOf .您可以使用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. Integer类有一个valueOf方法,它接受一个字符串作为值并返回一个int值,你可以使用它。 It will throw an NumberFormatException if the string passed to it is not a valid integer value.如果传递给它的字符串不是有效的整数值,它将抛出NumberFormatException

Also If you are using java5 or higher you can try using generics to make the code more readable.此外,如果您使用的是 java5 或更高版本,您可以尝试使用泛型使代码更具可读性。

You can implement the same using Generics , which would be easier.您可以使用Generics实现相同的功能,这会更容易。

List<Integer> numbers = new ArrayList<Integer> ();
Integer[] array = numbers.toArray (new Integer [10]);

试试 commons-lang

org.apache.commons.lang.ArrayUtils.toPrimitive(Integer[])

You can't call .intValue() on an Object , as the Object class lacks the method intValue() .您不能在Object上调用.intValue() ,因为Object类缺少方法intValue()

Instead, you need to cast the Object to the Integer class first, like so:相反,您需要先将Object转换为Integer类,如下所示:

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

Edit: Just a helpful tip on StackOverflow - please limit your code to what's relevant!编辑:只是关于 StackOverflow 的一个有用提示 - 请限制您的代码为相关内容! 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.它目前已被弃用,正在燃烧过程中。

I know this is pretty late, but here are my 2 cents!!我知道这已经很晚了,但这是我的 2 美分!!

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];
}

I made this method... I think is better! 我做了这个方法......我觉得更好!

public int[] ToMixArray(Object[] Array, int StratIndex, int Valuedefault, int NewLength){

    int[] res=new int[NewLength];
    for (int i = 0; i < NewLength; i++) {
        try { res[i]=Integer.parseInt(String.valueOf(Array[StratIndex+i]));}
        catch(Exception e){res[i]=Valuedefault;}
    }return res;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM