2013-01-16 16 views
6

Sembra che non ci sia un modo semplice per farlo, ma questo è quello che ho fatto finora e se qualcuno potesse correggerlo per farlo funzionare sarebbe grandioso. A "newarray [e] = array [i] .intValue();" ottengo un errore "Non è stato trovato alcun metodo chiamato" intValue "nel tipo" java.lang.Object "." Aiuto!Conversione di una matrice Object [] in una matrice int [] in java?

/* 
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 

}

+1

Perché si crea un array di 'Object' in primo luogo? –

+0

perché non avevo scelta, non mi permetteva di convertire ArrayList in un array int direttamente. – javanoob

+0

Si potrebbe usare una matrice di 'Intero'. –

risposta

2

Non è possibile chiamare .intValue() su un Object, come la classe Object manca il metodo intValue().

Invece, è necessario lanciare il Object alla classe Integer prima, in questo modo:

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

Edit: Solo un consiglio utile su StackOverflow - si prega di limitare il codice per ciò che è rilevante! Anche se a volte sono necessari grandi blocchi di codice, in questo caso non lo era. Rende la domanda più gradevole ed è destinata a ottenere risposte migliori in questo modo.

Inoltre, si prega di non utilizzare il tag . Attualmente è deprecato ed è in fase di burnination.

+0

Grazie, volevo solo che le risposte fossero più accurate visto che ho cercato su questo sito per ore per un soluzione e non ho trovato nulla. Ho provato il tuo suggerimento e ha detto java.lang.ClassCastException a quella riga ... – javanoob

8

È possibile utilizzare Integer.valueOf.

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

La classe Integer ha un metodo valueOf che prende una stringa come valore e restituisce un valore int, è possibile utilizzare questo. Lancia un NumberFormatException se la stringa passata non è un valore intero valido.

Anche se si utilizza java5 o superiore, è possibile provare a utilizzare generics per rendere il codice più leggibile.

+0

Sto mettendo in discussione l'efficienza di questa soluzione (non come se importi significativamente in questo caso). C'è un vantaggio nel lanciare '(String)' quindi usare 'Integer.valueOf()' su '(Integer)' quindi 'intValue()' che non vedo? – Zyerah

+0

Il problema è 'array' non è un 'Interger []' è un 'Object []' che contiene i valori di 'String' così' (Integer) array [i] 'dovrebbe lanciare un'eccezione cast di classe. –

+0

Appena testato, nessuna eccezione lanciata qui. Istruzione '((intero) x [1]).intValue() 'restituisce il valore appropriato dove' x' è una matrice di tipo 'Object []' e 'x [1]' non è nullo. – Zyerah

4

è possibile implementare la stessa utilizzando Generics, che sarebbe più facile.

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

Ogni volta che provo a utilizzare qualsiasi codice con "< >" ottengo "operatore di assegnazione non valido". Sai perché/come risolvere? – javanoob

+0

Stai usando java5 o versione successiva ... Generics è supportato solo da java5 ... – Jayamohan

+0

Suppongo di no, sto usando qualcosa chiamato "Ready to Program" per java – javanoob

1

hanno una prova commons-lang

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

Non ho idea di come andare a fare qualsiasi cosa questo significa. Scusa, ho una tremenda comp.sci. insegnante. – javanoob

0

Ho fatto questo metodo ... Credo che è meglio!

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; 
} 
Problemi correlati