Mit Arrays rechnen

Flutscho

Mitglied
Hallo

Ich habe folgendes Programm geschrieben:

Java:
import java.text.DecimalFormat;
public class AmeiseKorr
{
	public static void main (String [] args)
	{
		DecimalFormat df = new DecimalFormat("0.000");
		int input = 0, input2 = 0, ants, control, control2;
		
		String FormatcoordA1 = "0", FormatcoordA2 = "0", FormatcoordB1 = "0", FormatcoordB2 = "0"; 
		String Formatc_way1 = "0", Formatc_way2 = "0", Formatc_Distance = "0", Formatdistance_Ants = "0";
		
		do
		{
			System.out.print("\n" + "Moechten Sie eine Ameise oder 2 Ameisen laufen lassen?");
			System.out.print("\n" + "Sie koennen das Programm mit einer Eingabe <= 0 abbrechen!" );
			System.out.print("\n" + "Druecken Sie die 1 fuer eine Ameise oder die 2 fuer zwei Ameisen: ");
			ants = Input.readInt();
			
			do
			{
				double coordX = 0, coordY = 0, coord_A = 0, coordA = 0, coordA1 = 0, coordA2 = 0; 
				double coord_B = 0, coordB = 0, coordB1 = 0, coordB2 = 0;
				double c_wa = 0, c_way = 0, c_way1 = 0, c_way2 = 0, c_Distance = 0, distance_Ants = 0;
				
				if ( ants == 1 )
				{
					System.out.print("\n" + "Anzahl von Schritten? (Abbruch mit <= 0): " );
					input = Input.readInt();
				}
				if ( ants == 2 )
				{
					System.out.print("\n" + "Anzahl der Schritte von Ameise Eins (Abbruch mit <= 0): " );
					input = Input.readInt();
					System.out.print("\n" + "Anzahl der Schritte von Ameise Zwei (Abbruch mit <= 0): " );
					input2 = Input.readInt();
				}
				control = input;
				control2 = input2;
				
				while ( control >= 1 )
				{
					coordA =  Math.random() + Math.random() * (-1);
					coordA1 += coordA;
					coordB = Math.random() + Math.random() * (-1);// Zufallszahl zwischen -1 und 1 erstellen
					coordB1 += coordB;
					
					c_way = Math.sqrt( Math.pow( coordA, 2 ) + Math.pow( coordB, 2 ) );
					c_way1 += c_way;
					
					control--;
					//System.out.println(coordA + "       " + coordB);
				}
				
				while ( control2 >= 1 )
				{
					coord_A = Math.random() + Math.random() * (-1);
					coordA2 += coord_A;
					coord_B = Math.random() + Math.random() * (-1);
					coordB2 += coord_B;
					c_wa = Math.sqrt( Math.pow( coord_A, 2 ) + Math.pow( coord_B, 2 ) );
					c_way2 += c_wa;
					
					control2--;
					//System.out.println(coord_A + "       " + coord_B);
				}
				if ( ants == 1 && input >= 1 )
				{
					c_Distance = Math.sqrt( Math.pow( coordA1 - coordX, 2 ) + Math.pow( coordB1 - coordY, 2));
					
					FormatcoordA1 = df.format(coordA1);
					FormatcoordB1 = df.format(coordB1);
					Formatc_way1 = df.format(c_way1);
					Formatc_Distance = df.format(c_Distance);
					
					System.out.print( "\n" + "Endposition (x,y): " + FormatcoordA1 + ", " + FormatcoordB1 );
					System.out.print( "\n" + "Der zurueckgelegte Weg der Ameise betraegt: " + Formatc_way1);
					System.out.print( "\n" + "Distanz von (0,0): " + Formatc_Distance + "\n");
				}
				
				if ( ants == 2 && input >= 1 && input2 >= 1 )
				{
					distance_Ants = Math.sqrt( Math.pow(coordA1 - coordA2, 2 ) + Math.pow(coordB1 - coordB2, 2) );
					
					FormatcoordA1 = df.format(coordA1);
					FormatcoordB1 = df.format(coordB1);
					Formatc_way1 = df.format(c_way1);
					FormatcoordA2 = df.format(coordA2);
					FormatcoordB2 = df.format(coordB2);
					Formatc_way2 = df.format(c_way2);
					Formatdistance_Ants = df.format(distance_Ants);
					
					System.out.print("\n" + "Endposition Ameise 1 (x,y): " + FormatcoordA1 + ", " + FormatcoordB1 );
					System.out.print("\n" + "Weg Ameise 1: " + Formatc_way1 );
					System.out.print("\n" + "Endposition Ameise 2 (x,y): " + FormatcoordA2 + ", " + FormatcoordB2 );
					System.out.print("\n" + "Weg Ameise 2: " + Formatc_way2 );
					System.out.print("\n" + "Distanz zwischen Ameise 1 und Ameise 2: " + Formatdistance_Ants );
				}	
			} while ( input > 0 );
		} while ( ants >= 1 );
	}
}

Ich habe in dem Programm sehr viele Variablen, ich dachte jetzt ich könnte das Programm durch ein Array vereinfachen, also habe ich mir Grundwissen zu Arrays angeignet.

Mein Problem ist jetzt folgendes: Wie kann man denn mit Arrays rechnen?
Ich habe mein Array erstmal deklariert:

Java:
int x = 0, y = 0;
double[] coord1 = new double[7]; 
double[] coord2 = new double[7];

Ich möchte jetzt folgende Berechnung, mithilfe des Arrays machen:

Java:
while ( control >= 1 )
				{
					coordA =  Math.random() + Math.random() * (-1);
					coordA1 += coordA;
					coordB = Math.random() + Math.random() * (-1);// Zufallszahl zwischen -1 und 1 erstellen
					coordB1 += coordB;
					
					c_way = Math.sqrt( Math.pow( coordA, 2 ) + Math.pow( coordB, 2 ) );
					c_way1 += c_way;
					
					control--;
					//System.out.println(coordA + "       " + coordB);
				}

Leider habe ich keinen Peil, wie ich das machen soll :bahnhof:
Wie kann ich denn gezielt ein Feld im Array ansprechen und zu einer bereits gespeicherten Variablen was dazu addieren?
Meinen ersten Versuch habe ich mir jetzt erstmal aus Java von Kopf bis Fuß abgekupfert, aber ich kann mir nicht vorstellen, dass es so klappt. Kann mir vllt. jemand von euch auf die Sprünge helfen?

Java:
while ( x < input )
				{
					coord1[x] = new coord();
					coord1[x].coordA =  Math.random() + Math.random() * (-1);
					coord1[x].coordA1 += coord1[x].coordA;
					coord1[x].coordB = Math.random() + Math.random() * (-1);// Zufallszahl zwischen -1 und 1 erstellen
					coord1[x].coordB1 += coord1[x].coordB;
					
					coord1[x].c_way = Math.sqrt( Math.pow( coordA, 2 ) + Math.pow( coordB, 2 ) );
					coord1[x].c_way1 += coord1[x].c_way;

LG
 
Der Source ist mir jetzt ein wenig zu lang, aber allgemein rechnen geht so:

Java:
int x = array[0];
int y = array[1];
array[2] = x + y;

oder direkt:

Java:
array[2] = array[0] + array[1];

Also genauso wie "normale" Variablen, eben mit Feldangaben danach. Aber sonst gibt es eigendlich keinen Unterschied.
Nur solltest du bei deinen Source mehr auf Methoden oder sogar mehrere Klassen setzen.
 
Java:
double[][] coord1 = new double[7][2]; 
double[][] coord2 = new double[7][2];


                    coord1[0][0] =  Math.random() + Math.random() * (-1);
                    coord1[0][1] += coord1[0][0];
                    coord1[1][0] = Math.random() + Math.random() * (-1);// Zufallszahl zwischen -1 und 1 erstellen
                    coord1[1][1] += coord1[1][0];
so in etwa 🙂

edit: korrektur. coord 1 und coord 2 könnte man duch eine weitere ebene auch noch zusammenfassen und

Java:
double[][][] coord = new double[2][7][2]; 


                    coord[0][0][0] =  Math.random() + Math.random() * (-1);
                    coord[0][0][1] += coord[0][0][0];
                    coord[0][1][0] = Math.random() + Math.random() * (-1);// Zufallszahl zwischen -1 und 1 erstellen
                    coord[0][1][1] += coord[0][1][0];
darauß machen
 
Zuletzt bearbeitet von einem Moderator:
Hallo

Danke für deine Antwort. Warum hast du 2 eckige Klammern gemacht? Macht man das nicht nur bei mehrdimensionalen Arrays?

Kann ich mir nach dem Array dieses .coordxx sparen? In dem Beispiel aus dem ichs erstmal abgekupfert habe, wurde der Punktoperator verwendet, aber ich kann doch einfach über den Index das Array ansprechen oder nicht?

@Volvagia

Ja ich sollte Methoden / Objekte und alles nutzen, ich bin noch Anfänger, wir nutzen momentan nur die main Methode. In 2-3 Wochen kommen ändert sich das ganze dann
 
Beschreib' erstmal genauer, worum es da geht. Klingt als würdest du auf etwas hinarbeiten wollen, was am Ende eher aussieht wie
Java:
Ant ants[] = new Ant[n];
for (int i=0; i<n; i++)
{
    ants[i] = new Ant();
}

...

for (int i=0; i<steps; i++)
{
    ant[x].makeStep();
}


System.out.println("Endposition: "+ant.getPositionString());


EDIT: Wobei man DA sogar eher eine List verwenden würde.
 
Hallo

Ich soll im Prinzip eine oder 2 Ameisen in einem 2D Koordinaten System per Zufallszahl Schritte machen lassen. Die Anzahl der Schritte soll vom Nutzer eingegeben werden. Soll die Ameise 5 Schritte machen, sollen 5 Zufallszahlen addiert werden. Weiters soll man ausrechnen, wie weit die Ameise gelaufen ist und wie weit sie sich vom Startpunkt (0,0) wegbewegt hat (mit Pythagoras)

Arraylist ist auf jeden Fall viel zu vertieft. Ich wollte das mit den Arrays nur mal ausprobieren, weils jetzt im Unterricht dran kommt.

MfG
 
ah okay, also hast du 6 double werte je ameise.
wenn du in einem feld nur ein Coord() objekt speicherst kansnt du dir das array sparen. sonst würde halt ein deinem beispiel ein array ganz gut sein. (2D wenn du dir coord und coord2 sparen willst)

Java:
double[] coord = new double[6];

                while ( control >= 1 )
                {
                    coord[0] =  Math.random() + Math.random() * (-1);
                    coord[1] += coord[0];
                    coord[2] = Math.random() + Math.random() * (-1);// Zufallszahl zwischen -1 und 1 erstellen
                    coord[3] += coord[2];
                    
                    coord[4] = Math.sqrt( Math.pow( coord[0], 2 ) + Math.pow( coord[2], 2 ) );
                    coord[5] += coord[4];
                    
                    control--;
                    //System.out.println(coord[0] + "       " + coord[2]);
                }
für ameise 2 entsprechend mit coord2[]
 
Hallo

Danke für die Hilfe

Ich werde das jetzt gleich umsetzen. Leider wird das Programm dadurch weder kürzer, noch einfacher zu schreiben :/ Ob ich jetzt 14 Variablen schreibe oder 2 Arrays macht gar keinen Unterschied.

edit: Wobei ich mir die Suche nach verständlichen Variablennamen schon spare. Neue Variablen einzufügen geht auch schneller 😀


Eine Frage tut sich jetzt doch noch auf. Kann man mit dem Package DecimalFormat die Werte innerhalb der Arrays genau so anpassen wie bei einfachen Variablen?

MfG
 
Zuletzt bearbeitet:
oben in der variablendefinition machts nen unterschied^^

das hier könnte man zb
Java:
                control = input;
                control2 = input2;
                
                while ( control >= 1 )
                {
                    coordA =  Math.random() + Math.random() * (-1);
                    coordA1 += coordA;
                    coordB = Math.random() + Math.random() * (-1);// Zufallszahl zwischen -1 und 1 erstellen
                    coordB1 += coordB;
                    
                    c_way = Math.sqrt( Math.pow( coordA, 2 ) + Math.pow( coordB, 2 ) );
                    c_way1 += c_way;
                    
                    control--;
                    //System.out.println(coordA + "       " + coordB);
                }
                
                while ( control2 >= 1 )
                {
                    coord_A = Math.random() + Math.random() * (-1);
                    coordA2 += coord_A;
                    coord_B = Math.random() + Math.random() * (-1);
                    coordB2 += coord_B;
                    c_wa = Math.sqrt( Math.pow( coord_A, 2 ) + Math.pow( coord_B, 2 ) );
                    c_way2 += c_wa;
                    
                    control2--;
                    //System.out.println(coord_A + "       " + coord_B);
                }

durch

Java:
        int numberOfAnts = 2;
        int[] control = new int[numberOfAnts];
        control[0] = input;
        control[1] = input2;
        
        double coord[][] = new double[numberOfAnts][6];

        for (int i = 0; i < numberOfAnts; i++) {
            while ( control[i] >= 1 )
            {
                coord[i][0] =  Math.random() + Math.random() * (-1);
                coord[i][1] += coord[i][0];
                coord[i][2] = Math.random() + Math.random() * (-1);// Zufallszahl zwischen -1 und 1 erstellen
                coord[i][3] += coord[i][2];
                
                coord[i][4] = Math.sqrt( Math.pow( coord[i][0], 2 ) + Math.pow( coord[i][2], 2 ) );
                coord[i][5] += coord[i][4];
                
                control[i]--;
            }
        }
ersetzen^^ musste nur die variablen hochsortieren

Eine Frage tut sich jetzt doch noch auf. Kann man mit dem Package DecimalFormat die Werte innerhalb der Arrays genau so anpassen wie bei einfachen Variablen?
mit
Java:
int [] i = new int[5];
i[1] = 5;
mit dem i[1] kannst du alles machen wie mit jedem einzelnen int auch. die einzelnen array werte sind ja nicht anderes als durchnummerierte variablen eines types
 
Zuletzt bearbeitet von einem Moderator:
Wenn man int numberOfAnts von der Tastatur einlesen lässt, könnte man dann nicht beliebig viele Ameisen laufen lassen? Dein Programmstück berechnet ja gleich für beide Varianten die Koordinaten, das ist echt gut, das gefällt mir 😀

Java:
String FormatcoordA1 = "0", FormatcoordA2 = "0", FormatcoordB1 = "0", FormatcoordB2 = "0"; 
String Formatc_way1 = "0", Formatc_way2 = "0", Formatc_Distance = "0", Formatdistance_Ants = "0";

kann man aber nicht einfach mit folgendem ersetzen, das mag der Compiler gar nicht:

Java:
String Formatcoord1[1] = "0", Formatcoord2[1] = "0", Formatcoord1[3] = "0", Formatcoord2[3] = "0"; 
String Formatcoord1[5] = "0", Formatcoord2[5] = "0", Formatcoord1[6] = "0", Formatcoord2[6] = "0";
 
erst array definieren, dann werte zuweisen

bei 2 ameisen:
Java:
 String[][] formatCoord = new String [numberOfAnts][3];
for (int i = 0; i < numberOfAnts; i++) {
    for (int j = 0; j < 3; j++){
        formatCoord[i][j] = "0";
    }
}



                    //unten dann das so umstellen:
               for (int i = 0; i < numberOfAnts; i++) {
                    formatCoord[i][0] = df.format(coord[i][1]);
                    formatCoord[i][1] = df.format(coord[i][3]));
                    formatCoord[i][2] = df.format(coord[i][5]));
               }
                    // distance bleibt alleine, ist ja nur auf 2 ameisen bezogen, auch wenn da 10 rumrennen, rechnet man halt die entfernen zwischen 2 bestimmten aus
                    String Formatdistance_Ants = df.format(distance_Ants);

im anhang kannst du dir das ganze in gut angucken^^ aber wie es so ist, selber denken ist besser. mein beispiel funktioniert mit bis zu 2 mrd ameisen, das wäre dann ein gesamter bau

ich hab nur Input durch Scanner ersetzt. Macht vermutlich das gleiche, habe Input nicht.
 

Anhänge

Zuletzt bearbeitet von einem Moderator:
Hallo nochmal

Danke für deine ausführliche Schilderung, ich sehs mir gleich mal genauer an.

Bei mir murrt der Compiler momentan noch rum, weil ich beim formatieren double werte habe und keine int.

LG
 

Zurück
Oben