sept.
2010
Java Quiz #42 : A string too far
(FR)
Ce code semble totalement inoffensif, mais peut causer des erreurs sous certaines circonstances.
Pouvez-vous détecter le problème ?
(EN)
This code may seem harmless, but will cause serious problems in certain circumstances.
Can you spot the problem ?
public class Quiz42 { public static void main(String[] args) { new Quiz42(); } private static final int MAX_STRING_LENGTH = 6; private Map<Integer, String> db = new HashMap<Integer, String>(); private int nextId = 0; public Quiz42() { // Introductory text Console console = System.console(); if (console==null) { System.out.println("Don't cheat in Eclipse :)"); System.exit(0); } console.printf( "FakeDB 1.0%n"+ "'exit': exits FakeDB.%n" + "'db' : dumps the DB content.%n"+ "Words are limited to %d characters.%n%n> ",MAX_STRING_LENGTH); // Read - Eval loop String s = null; while ((s = console.readLine()) != null) { if ("exit".equals(s)) { break; } if ("db".equals(s)) { console.printf("DB content : %s%n",db); continue; } // Check DB constraints client-side, then save the user's string. if (s.length() > MAX_STRING_LENGTH) { console.printf("String too long, please enter another one.%n"); continue; } persistInDatabase(s.toUpperCase()); console.printf("Saved '%s'.%n> ",s); } } private void persistInDatabase(String s) { // Simulate a database constraint if (s.length() > MAX_STRING_LENGTH) { throw new IllegalArgumentException("DATA TOO LARGE"); } db.put(nextId++, s); } }