PHP-Code zu Java-Code

Aracher17

Mitglied
Moin, Moin!

Ich habe hier im Forum schon sehr viel gutes gelesen und nun beschlossen mich auch zu regestrieren und euch gleich meine aller erste Frage zustellen. Ich hoffe die ist hier auch richtig?!

Ich habe einst etwas in PHP programmiert. Allerdings läuft der Script in PHP nicht so Leistungsfähig , wie ich es mir in Java vorstelle. Deswegen wollte ich es in Java umschreiben. Allerdings stellen sich mir hier auch schon die ersten Hindernisse.

Hier ist der PHP-Code:
PHP:
    function permute($keys,$limit = 3, $list = array( ))
    {
	$file = "lists/".$limit."-ist.txt";
	if(!file_exists($file))
	{
	//create file if it dosent exists
	$ourFileHandle = fopen($file, 'w') or die("can't open file");
	fclose($ourFileHandle);
	}

   if(count($list) === $limit) 
  { 
    //echo implode('', $list) . "<br>\n";         // Array in String wandeln trennzeichen ist Leerzeichen 
	array_push($this->permuteArray, implode($list));
	//file_put_contents($file,$this->permuteArray, FILE_APPEND);
	$handle = fopen($file, "a") or die("Cannot open file!");
	fwrite($handle, "\n".implode("", $list));
	fclose($handle);
  } 
  for ($i = count($keys) - 1; $i >= 0; --$i) 
  { 
    $pkeys = $keys;                              // Orginal Array String liste beibehalten nicht überschreiebn 
    $perm  = $list; 
    list($foo) = array_splice($pkeys, $i, 1);    // Wandeln zum String durch list Einzelen alle Zeichen rausholen Zeichenlänge auf 1 begrenzen 
    array_unshift($perm, $foo);                  // fügt die übergebenen Elemente am Anfang von array ein 
 //   permute($pkeys, $perm); 
    if(count($perm) <= $limit) 
    { 
      $this->permute($pkeys,$limit,$perm);              // Rekusiver aufruf 
    } 
  }

    } //function permute

Das habe ich in Java jetzt so umgeschrieben:
Java:
	private void permute(final List<String> keys,final int limit, final List<String> list) {
		//Runnable r = new Runnable() {

		//		@Override
		//		public void run() {
					txtLog.append("\n"+"Start permuting");
					System.out.println("Keys: " + keys + " || limit: " + limit);
					if(keys.size() == limit) {
						//write into file
						try {
						BufferedWriter output = new BufferedWriter(new FileWriter(tmpFile));
						String[] foo = (String[]) list.toArray();
						output.write("\n"+implode("",foo));
						output.close();
						txtLog.append("\n"+"Writting...");
						} catch (IOException e) {
							JOptionPane.showMessageDialog(null, "Fehler beim erstellen der temporären Datei!","Fehler",JOptionPane.CANCEL_OPTION);
							System.err.print("FEHLER! >> " + e.getMessage());
							e.printStackTrace();
						}
					}
						
						for(int i = keys.size() - 1; i >= 0; --i) {
							System.out.println("I'am inside a looop!");
							
							List<String> pkeys = keys;
							List<String> perm  = list;
							
							List<String> foos = pkeys.subList(0, i+1);
							System.out.println("foos: " + foos);
							perm.addAll(foos);
							
							if(perm.size() <= limit)
							{
								permute(pkeys,limit,perm); // Rekusiver aufruf
								System.out.println("I'am inside a rekusiv!");
							}
						}
					
	//			}
	//		};
	//		Thread t = new Thread(r);
	//		t.start();
	}
	
	public static String implode(String separator, String... data) {
	    StringBuilder sb = new StringBuilder();
	    for (int i = 0; i < data.length - 1; i++) {
	    //data.length - 1 => to not add separator at the end
	        if (!data[i].matches(" *")) {//empty string are ""; " "; "  "; and so on
	            sb.append(data[i]);
	            sb.append(separator);
	        }
	    }
	    sb.append(data[data.length - 1]);
	    return sb.toString();
	}

Aufrufen tue ich die Methode wie folgt:
Java:
					//start permuatation
					String[] zeichenkette = txtZeichen.getText().toString().split("");
					List<String> zeichenketteListe = Arrays.asList(zeichenkette);
					permute(zeichenketteListe, Integer.parseInt(txtLimit.getText().toString()),null);

Leider funktioniert es natürlich nicht so wie es soll. Ich bekomme hierbei folgende Fehlermeldung:#
Code:
Keys: [, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, *, !, $, %, &, /, (, ), =, ?, +, -, _, ., ,, :, ;, #] || limit: 2
I'am inside a looop!
foos: [, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, *, !, $, %, &, /, (, ), =, ?, +, -, _, ., ,, :, ;, #]
java.lang.NullPointerException
	at de.systemoverride.percalc.MainDialog.permute(MainDialog.java:202)
	at de.systemoverride.percalc.MainDialog.btnStartActionPerformed(MainDialog.java:158)
	at de.systemoverride.percalc.MainDialog.access$0(MainDialog.java:130)
	at de.systemoverride.percalc.MainDialog$2.actionPerformed(MainDialog.java:100)
	at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
	at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
	at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
	at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
	at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
	at java.awt.Component.processMouseEvent(Unknown Source)
	at javax.swing.JComponent.processMouseEvent(Unknown Source)
	at java.awt.Component.processEvent(Unknown Source)
	at java.awt.Container.processEvent(Unknown Source)
	at java.awt.Component.dispatchEventImpl(Unknown Source)
	at java.awt.Container.dispatchEventImpl(Unknown Source)
	at java.awt.Component.dispatchEvent(Unknown Source)
	at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
	at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
	at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
	at java.awt.Container.dispatchEventImpl(Unknown Source)
	at java.awt.Window.dispatchEventImpl(Unknown Source)
	at java.awt.Component.dispatchEvent(Unknown Source)
	at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
	at java.awt.EventQueue.access$200(Unknown Source)
	at java.awt.EventQueue$3.run(Unknown Source)
	at java.awt.EventQueue$3.run(Unknown Source)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
	at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
	at java.awt.EventQueue$4.run(Unknown Source)
	at java.awt.EventQueue$4.run(Unknown Source)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
	at java.awt.EventQueue.dispatchEvent(Unknown Source)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
	at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
	at java.awt.EventDispatchThread.run(Unknown Source)

Ich hoffe ihr könnt mir helfen?!

MfG
Aracher17
 
Zuletzt bearbeitet:
NullPointerException heißt generell, dass etwas nicht initialisiert wurde.

Auf welche Zeile genau bezieht sich die Exception (-> welche Zeile des geposteten Codes ist die Original 202-te?)
 
[JAVA=202]perm.addAll(foos);[/code]

Hier im Kontext:
Java:
List<String> pkeys = keys;
List<String> perm  = list;
List<String> foos = pkeys.subList(0, i+1);
System.out.println("foos: " + foos);
perm.addAll(foos);
 
Zuletzt bearbeitet:
Du übergibst beim 1. Aufruf list = null, kopierst diese null in der Schleife nach perm und rufst dann etwas auf perm auf - deshalb die Exception.
 
Habe leider gerade mein PC nicht zur Verfügung, sonst würde ich meine Frage gerne selber testen.
Würde es was ändern, wenn ich im Sage, dass list eine leere Liste sein soll?
 

Zurück
Oben