|
|
|
![]() |
|
Strumenti |
![]() |
#1 |
Junior Member
Iscritto dal: Mar 2013
Messaggi: 18
|
[java]è efficente?(codice banale)
Ciao a tutti, ho da poco iniziato a studiare un po' Java dato che sono diplomato come perito informatico e sono a digiuno dalla programmazione da qualche anno..(secondo voi ne vale la pena per avere possibilità di lavoro?).
Ho due domande stupide su questo piccolo codice che ho fatto prima: -come mai se ometto l'ELSE l'IF non funziona nel modo corretto? non dovrebbe essere facoltativo se è presente solo un'istruzione 'alternativa' all'if? -a vederlo così il codice mi sembra ridondante e che si potrebbe scrivere in modi più efficenti..se si, come? Tnx Codice:
import javax.swing.*; public class es8 { public static void main (String argv[]) { int n; int j; int m; int k=Integer.parseInt(JOptionPane.showInputDialog(null,"inserisci un valore:")); for(int i=k;i>=2;i--) { System.out.print("\r"+i+" -> "); if(i%2==0) n=i/2; else n=((3*i)+1); System.out.print("f("+i+")="+n); for(j=n;j>1;) { System.out.print(" -> "); if(j%2==0) m=j/2; else m=((3*j)+1); System.out.print("f("+j+")="+m); j=m; } j=n; } } } |
![]() |
![]() |
![]() |
#2 |
Senior Member
Iscritto dal: Oct 2007
Città: Padova
Messaggi: 4131
|
Io l'ho fatto così:
Codice:
import java.util.*; import javax.swing.JOptionPane; /** * Computing Collatz sequences * see http://www.hwupgrade.it/forum/showthread.php?t=2554545 * * CollatzComputer * - launcher. Accepts a "gui" arguments to launch the GUI version, otherwise * - the Consolle version is used. * * CollatzGuiApp * - the GUI app. Use javax.swing.JOptionPane for input/output. * * CollatzConsolleApp * - the consolle app. Use java.io.System for input/output. * * CollatzSeq * - Istances of this class rappresent Collatz Sequences. * */ public class CollatzComputer { public static void main(String[] args) { if (args.length > 0 && "gui".equalsIgnoreCase(args[0])) { CollatzGuiApp.run(); } else { CollatzConsolleApp.run(); } } } class CollatzGuiApp { static void run() { String inputMsg = "Please, insert an integer N bigger than zero."; String errorMsg = "Invalid input!"; int n; while (true) { try { n = Integer.parseInt(JOptionPane.showInputDialog(null, inputMsg)); } catch (NumberFormatException ex) { JOptionPane.showMessageDialog(null, errorMsg); continue; } if (n > 0) break; }; StringBuilder buffer = new StringBuilder(); for (int i=n; i>0; i--) { CollatzSeq sequence = CollatzSeq.forInteger(i); buffer.append(sequence).append("\n"); } JOptionPane.showMessageDialog(null, buffer); } } class CollatzConsolleApp { static void run() { System.out.println("CollatzConsolleApp > Welcome."); Scanner scanner = new Scanner(System.in); scanner.useDelimiter("\n"); String inputMsg = "Please, insert an integer N bigger than zero."; String errorMsg = "Invalid input!"; int n; while (true) { System.out.println(inputMsg); try { n = Integer.parseInt(scanner.next()); } catch (NumberFormatException ex) { System.out.println(errorMsg); continue; } if (n > 0) break; }; for (int i=n; i>0; i--) { CollatzSeq sequence = CollatzSeq.forInteger(i); System.out.println(sequence); } System.out.println("End."); } } /** * A Collatz sequence. */ final class CollatzSeq implements Iterable<Integer> { /** * Compute the Collatz sequence for the integer n * @param n the first integer in the Collatz sequence to compute * @return the Collatz sequence starting from n to 1 inclusive */ static CollatzSeq forInteger(int n) { return new CollatzSeq(n); } // compute the Collatz sequence [n..1] - iterative method private static List<Integer> iterativeSequence(int n) { List<Integer> list = new ArrayList<>(); while (n > 1) { list.add(n); if (n % 2 == 0) { n = n/2; } else { n = 3*n + 1; } } list.add(1); return list; } // compute the Collatz sequence [n..1] - trampoline private static List<Integer> recursiveSequence(int n) { List<Integer> list = new ArrayList<>(); recursiveSequence0(n, list); return list; } // compute the Collatz sequence [n..1] - recursive method with accumulator private static void recursiveSequence0(int n, List<Integer> acc) { acc.add(n); if (n == 1) return; if (n % 2 == 0) { recursiveSequence0(n/2, acc); } else { recursiveSequence0(3*n+1, acc); } } // For testing purposes public static void main(String[] args) { CollatzSeq.test101(1); CollatzSeq.test101(4); CollatzSeq.test101(10); CollatzSeq.test101(79); CollatzSeq.test101(101); } private static void test101(int n) { CollatzSeq sequence = CollatzSeq.forInteger(n); System.out.println(sequence); System.out.println(sequence.count() + " elements"); System.out.println(""); } private final List<Integer> sequence; /** * Private 'ctor. * Use static method CollatzSeq.forInteger to create instances. */ private CollatzSeq(int n) { //List<Integer> list = recursiveSequence(n); List<Integer> list = iterativeSequence(n); sequence = Collections.unmodifiableList(list); } /** * @return the number of integers in this CollatzSeq */ public int count() { return sequence.size(); } @Override public String toString() { StringBuilder buffer = new StringBuilder().append("["); Iterator<Integer> it = sequence.iterator(); while (it.hasNext()) { buffer.append(it.next()); if (it.hasNext()) buffer.append(" -> "); } return buffer.append("]").toString(); } @Override public Iterator<Integer> iterator() { return sequence.iterator(); } }
__________________
As long as you are basically literate in programming, you should be able to express any logical relationship you understand. If you don’t understand a logical relationship, you can use the attempt to program it as a means to learn about it. (Chris Crawford) |
![]() |
![]() |
![]() |
Strumenti | |
|
|
Tutti gli orari sono GMT +1. Ora sono le: 18:32.