müsste String.substring(...)
verwenden, um diese Arbeit zu machen. Das und eine for
Schleife.
Ich werde im Rest des Codes bearbeiten.
Herausgegeben in. Erläuternde Kommentare hinzugefügt.
public static void main(String[] args) {
// Just for testing.
StringGrouper grouper = new StringGrouper();
// Have tested for 2, 3, 4, and 5
List<Long> output = grouper.makeList(12892374897L, 4);
// Sends out the output. Note that this calls the List's toString method.
System.out.println(output);
}
/**
* @param l
* @param spacing
*/
private List<Long> makeList(long l, int spacing) {
List<Long> output = new ArrayList<>(Math.round(l/spacing));
String longStr = String.valueOf(l);
// System.err.println(longStr);
for (int x = 0; x < longStr.length(); x++) {
// When the remainder is 0, that's where the grouping starts and ends
if (x % spacing == 0) {
// If it does not overflow, send it in
if ((x + spacing) < longStr.length()) {
String element = longStr.substring(x, x + spacing);
// System.err.println(element);
output.add(Long.parseLong(element));
} else {
// If it does overflow, put in the remainder
output.add(Long.parseLong(longStr.substring(x, longStr.length())));
}
}
}
return output;
}
Ihre Frage ist unterspezifiziert. Das Aufteilen einer Zahl auf jede "n" Ziffer ist als Voraussetzung nicht ausreichend. Sie müssen angeben, ob die Gruppierung von links oder von rechts erfolgt, d. H. Was möchten Sie, wenn die Anzahl der Stellen kein genaues Vielfaches von "n" ist. Kommt das kurze Unterergebnis von links oder rechts in der ursprünglichen Nummer? Außerdem hat "Long.MAX_VALUE" nur 19 Ziffern, ist "Long" breit genug für Ihre "langen" Zahlen? Solltest du stattdessen 'BigInteger' verwenden? –