public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); short L = Short.parseShort(br.readLine()); short R = Short.parseShort(br.readLine()); short out = maxXor(L, R); System.out.print(out); }
public static short datoShort() { try { return Short.parseShort(dato()); } catch (NumberFormatException e) { return Short.MIN_VALUE; // valor más pequeño } }
public static void main(String[] args) throws IOException { File input = new File(args[0]); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(input))); File output = new File(input.getParentFile(), input.getName() + ".out"); PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(output))); short numberOfCases = Short.parseShort(reader.readLine()); for (short c = 0; c < numberOfCases; ++c) { TreeMap<Short, TreeSet<Short>> intranet = new TreeMap<>(); short countOfRope = Short.parseShort(reader.readLine()); int intersectionCount = 0; for (short r = 0; r < countOfRope; ++r) { String line = reader.readLine(); String[] words = line.split(" "); short leftEndPoint = Short.parseShort(words[0]); short rightEndPoint = Short.parseShort(words[1]); for (Map.Entry<Short, TreeSet<Short>> e : intranet.entrySet()) { short l = e.getKey(); TreeSet<Short> rSet = e.getValue(); if (leftEndPoint < l) { Short res = rSet.lower(rightEndPoint); if (res != null) { intersectionCount += rSet.headSet(res, true).size(); } } else { // leftEndPoint > l Short res = rSet.higher(rightEndPoint); if (res != null) { intersectionCount += rSet.tailSet(res, true).size(); } } } // put TreeSet<Short> rights; if (intranet.containsKey(leftEndPoint)) { rights = intranet.get(leftEndPoint); } else { rights = new TreeSet<>(); intranet.put(leftEndPoint, rights); } rights.add(rightEndPoint); } writer.println("Case #" + (c + 1) + ": " + intersectionCount); } reader.close(); writer.close(); }
/** Lee un <CODE>short</CODE> introducido por el teclado. */ public static final synchronized short readShort() { input = ""; short value = Short.MIN_VALUE; try { input = in.readLine(); } catch (IOException e) { error("standard input"); } try { value = Short.parseShort(input); } catch (NumberFormatException e) { error("Invalid int format"); } return value; }
// Get property value as a short public short getShort(String key) { return (properties.containsKey(key)) ? Short.parseShort(properties.get(key).toString()) : 0; }
public static void main(String[] args) throws IOException { Scanner keyboard = new Scanner(System.in); String input = null; // for most of the input String fileName = "Tasks.txt"; // file were stuff is written to short menu = 0; // for the short input Date date = new Date(); // for the stupid date int modTask = 0; // for getting a task's position in the array int numTasks = 0; // keeps count of number of tasks added to task list TaskList otherStuff = new TaskList(); // TASK LIST!! System.out.println("Welcome to the Task Manager!"); // A spiff little menu System.out.println("Would you like to: "); System.out.println("1. Load a task list from file"); System.out.println("2. Save a new task list"); System.out.println("3. Add a task"); System.out.println("4. Remove a task"); System.out.println("5. Edit a task"); System.out.println("6. Search tasks"); System.out.println("7. Sort tasks by priority"); System.out.println("8. Print task list"); System.out.println("9. Exit program"); menu = keyboard.nextShort(); switch (menu) { // Switch, switch, switch! case 1: // to load the file try { otherStuff.readFile(fileName); } catch (FileNotFoundException e) { System.out.println("File \"" + fileName + "\" not found!"); System.out.println("Dying...."); e.printStackTrace(); System.exit(-1); } break; case 2: // for making a new Task list and then saving it to disk do { Task stuff = new Task(); // creating a new task System.out.print("Description: "); input = keyboard.nextLine(); stuff.setDescription(input); // setting description System.out.print("Priority(1-3): "); input = keyboard.nextLine(); // setting priority by converting string to short stuff.setPriority(Short.parseShort(input)); System.out.println("Category(1-5): "); System.out.println("1. Other\n2. School\n3. Personal\n4. Chore\n5. Work"); input = keyboard.nextLine(); // setting priority by converting string to short stuff.setCategory(Short.parseShort(input)); System.out.print("Location: "); input = keyboard.nextLine(); stuff.setLocation(input); // setting location /* * Date gets an extra separating space because it is actually a little evil * and might corrupt the rest of the program. */ System.out.print("Due Date (ex. 01/12/2015): "); input = keyboard.nextLine(); // now things get a little weird... // splitting the string where character "/" appears // This needs a string array to hold the three strings String[] dateParts = input.split("/"); // setting first part of split string (which is month in America) int month = Integer.parseInt(dateParts[0]); // setting second part of string to day (America and stuff) int day = Integer.parseInt(dateParts[1]); // setting the third part of the string to year int year = Integer.parseInt(dateParts[2]); // plugging in the newly parsed integers into Gregorian Calendar spiffiness GregorianCalendar gCal = new GregorianCalendar(year, month, day); // converting Gregorian Calendar into date!! date = gCal.getTime(); // SETTING THAT DATE WITH SOME WICKED STYLE stuff.setDate(date); // finally, finally sets the date System.out.print("Completed? : "); // setting completed input = keyboard.nextLine().toLowerCase(); // doesn't matter how you enter the letter stuff.setCompleted(Boolean.parseBoolean(input)); // Parse that string! System.out.print("Add new task?"); input = keyboard.nextLine().toLowerCase(); otherStuff.addTask(stuff); // adds the task to the task list numTasks++; // keeping track of tasks in task list } while (input.equalsIgnoreCase("y")); // ignoring case otherStuff.printTasks(); // writing task list to disk try { otherStuff.writeFile(fileName); } catch (FileNotFoundException e) { // no file = sadness System.out.println("File \"" + fileName + "\" not found!"); System.out.println("Dying..."); e.printStackTrace(); System.exit(-1); } break; case 3: // adding a new task to the pre-existing task list // Same as before... Task stuff = new Task(); System.out.print("Description: "); // setting description input = keyboard.nextLine(); stuff.setDescription(input); System.out.print("Priority(1-3): "); // setting priority input = keyboard.nextLine(); stuff.setPriority(Short.parseShort(input)); // parsing to short System.out.print("Category(1-5): "); // setting category input = keyboard.nextLine(); stuff.setCategory(Short.parseShort(input)); // parse, parse System.out.print("Location: "); // setting location input = keyboard.nextLine(); stuff.setLocation(input); System.out.print("Due Date (ex. 01/12/2015): "); // date..-_- input = keyboard.nextLine(); String[] dateParts = input.split("/"); int month = Integer.parseInt(dateParts[0]); int day = Integer.parseInt(dateParts[1]); int year = Integer.parseInt(dateParts[2]); GregorianCalendar gCal = new GregorianCalendar(year, month, day); date = gCal.getTime(); stuff.setDate(date); // actually really happy with this date stuff in the end :) System.out.print("Completed? : "); // setting completed input = keyboard.nextLine().toLowerCase(); stuff.setCompleted(Boolean.parseBoolean(input)); otherStuff.addTask(stuff); // adding the task to the task list numTasks++; // adding one to number of tasks in task list cause we added a task break; case 4: // remove a task otherStuff.printTasks(); // print tasks so user knows what's where System.out.println( "Which task would you like to remove? " + "(Enter an interger starting with 0)"); // because arrays start with 0 modTask = keyboard.nextInt(); otherStuff.removeTask(modTask); // removing specified task break; case 5: // edit a task otherStuff.printTasks(); // print tasks so user knows what to edit System.out.println("Which task would you like to edit?"); modTask = keyboard.nextInt(); Task task = otherStuff.getTask(modTask); // modify specified task System.out.println("What would you like to edit?"); // getting all specific here System.out.println("1. Description"); System.out.println("2. Priority"); System.out.println("3. Category"); System.out.println("4. Location"); System.out.println("5. Due Date"); System.out.println("6. Completed?"); modTask = keyboard.nextInt(); switch (modTask) { // Modify what you want!! case 1: // change description System.out.print("New Description: "); task.setDescription(input); break; case 2: // change priority System.out.print("New Priority: "); task.setPriority(Short.parseShort(input)); break; case 3: // change category System.out.print("New Category: "); task.setCategory(Short.parseShort(input)); break; case 4: // change location System.out.print("New Location: "); task.setLocation(input); break; case 5: // change due date System.out.print("New Due Date: "); task.setDate(date); break; case 6: // change completed status System.out.print("Completed? "); task.setCompleted(Boolean.parseBoolean(input)); break; } break; case 6: // search tasks System.out.println("Would you like to search by: "); System.out.println("1. Category"); System.out.println("2. Priority"); System.out.println("3. Due date"); System.out.println("4. Location"); System.out.println("5. Completion"); menu = keyboard.nextShort(); // switch in a switch cause that's how I roll... switch (menu) { case 1: // searching by category otherStuff.searchByCategory(menu); break; case 2: // searching by priority otherStuff.searchByPriority(menu); break; case 3: // searching by due date otherStuff.searchByDueDate(date); break; case 4: // searching by location otherStuff.searchByLocation(input); break; case 5: // searching by completed status otherStuff.searchByCompleted(input); break; } break; case 7: // sort tasks // definitely the spiffiest sorting you have ever seen otherStuff.orderByPrio(); // print those amazingly sorted tasks now otherStuff.printTasks(); break; case 8: // print tasks otherStuff.printTasks(); break; case 9: // for those crazy people not absolutely in love with this program System.out.println("GOODBYE!"); keyboard.close(); // closing the keyboard System.exit(0); // actually exiting program } }
private void parseArtificial(Element artificialElement, ArtificialSatellite artificial) { artificial.setYear(Short.parseShort(getInnerTagContent(artificialElement, "year"))); parseSatellite(artificialElement, artificial); }
public MXRecord(Name _name, short _dclass, int _ttl, MyStringTokenizer st, Name origin) throws IOException { super(_name, Type.MX, _dclass, _ttl); priority = Short.parseShort(st.nextToken()); target = new Name(st.nextToken(), origin); }
public void run() { Socket sock = null; try { int code = StreamTokenizer.TT_EOL; FileReader reader = new FileReader(filename); StreamTokenizer tokenizer = new StreamTokenizer(reader); tokenizer.ordinaryChars('0', '9'); tokenizer.wordChars('0', '9'); tokenizer.slashSlashComments(true); System.out.println("Connecting to socket 10576."); try { sock = new Socket("127.0.0.1", 10576); System.out.println("Connection to socket 10576 established."); } catch (Exception e) { System.out.println( "Inputting packets from file must be done while running Tossim with the -ri option"); System.exit(-1); } DataOutputStream output = new DataOutputStream(sock.getOutputStream()); while (true) { code = tokenizer.nextToken(); if (code == tokenizer.TT_EOF) { break; } else if (code == StreamTokenizer.TT_EOL) { } else if (code == StreamTokenizer.TT_WORD) { String word = tokenizer.sval; long lval = Long.parseLong(word); code = tokenizer.nextToken(); if (code != StreamTokenizer.TT_WORD) { break; } word = tokenizer.sval; short sval = Short.parseShort(word); byte[] data = new byte[36]; for (int i = 0; i < 36; i++) { code = tokenizer.nextToken(); if (code != StreamTokenizer.TT_WORD) { break; } String datum = tokenizer.sval; try { data[i] = (byte) (Integer.parseInt(datum, 16) & 0xff); } catch (NumberFormatException e) { System.out.println(e); System.out.println(datum); } } output.writeLong(lval); output.writeShort(sval); output.write(data); } else if (code == StreamTokenizer.TT_NUMBER) { } } } catch (Exception exception) { System.err.println("Exception thrown."); exception.printStackTrace(); } finally { try { sock.close(); } catch (Exception e) { } } /// ServerSocket server = new ServerSocket(10576, 1); // System.out.println("Waiting on socket 10576."); // Socket sock = server.accept(); // System.out.println("Accepted connection from " + sock); // DataOutputStream input = new DataOutputStream(sock.getOutputStream()); }
private MineDoor(String[] args) { this.arguments = new ArgumentDispatcher(args); this.serverProperties = new ServerProperties(); this.getProperties().loadArgumentDispatcher(this.getArguments()); try { if (this.getArguments().getPropertiesFile().exists()) { FileReader reader = new FileReader(this.getArguments().getPropertiesFile()); this.getProperties().load(reader); reader.close(); } } catch (IOException e) { this.getLogger().warn("Unable to load configuration", e); } try { this.getProperties().save(); } catch (IOException e) { this.getLogger().warn("Unable to save configuration", e); } this.getLogger().info("Loading servers..."); File servers = this.getArguments().getServerList(); try { if (!servers.exists()) { if (this.getArguments().doNotCreateFile()) { throw new IOException("No new file creation"); } //noinspection ResultOfMethodCallIgnored servers.createNewFile(); PrintWriter writer = new PrintWriter(new FileWriter(servers)); writer.println("#MineDoor Monitoring server list"); writer.println("#Servers list in this file will be monitored by MineDoor"); writer.println("#e.g. 112.15.62.17:19132"); writer.close(); } BufferedReader reader = new BufferedReader(new FileReader(servers)); String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (line.startsWith("#") || line.isEmpty()) continue; try { String address = line; short port = 19132; if (line.contains(":")) { address = line.split(":")[0]; port = Short.parseShort(line.split(":")[1]); } this.monitor.addToMonitor(new InetSocketAddress(address, port)); } catch (Exception e) { this.getLogger().info("Unable to parse server list", e); } } reader.close(); } catch (IOException e) { this.getLogger().error("Unable to parse server list", e); } this.getLogger().info("Starting monitor..."); ServerMonitor.PING_FREQUENCY = this.getProperties().getUpdateFrequency(); this.monitor.start(); this.getLogger().info("Monitor running at " + this.monitor.getSocket().getLocalSocketAddress()); this.getLogger().info("Starting MineDoor at " + this.getProperties().getInterfaceAddress()); this.getInterface().start(this.getProperties().getInterfaceAddress()); }
// Scans the given file and creates symbols for its functions & label names. private void buildProgram(File file, Hashtable symbols) throws ProgramException { BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(file.getAbsolutePath())); } catch (FileNotFoundException fnfe) { throw new ProgramException("file does not exist"); } int lineNumber = 0; String line; String label; String instructionName; String currentFunction = null; short indexInFunction = 0; byte opCode; short arg0, arg1; short pc = nextPC; HVMInstructionSet instructionSet = HVMInstructionSet.getInstance(); isSlashStar = false; try { while ((line = unCommentLine(reader.readLine())) != null) { lineNumber++; if (!line.trim().equals("")) { StringTokenizer tokenizer = new StringTokenizer(line); instructionName = tokenizer.nextToken(); opCode = instructionSet.instructionStringToCode(instructionName); if (opCode == HVMInstructionSet.UNKNOWN_INSTRUCTION) throw new ProgramException( "in line " + lineNumber + ": unknown instruction - " + instructionName); switch (opCode) { case HVMInstructionSet.PUSH_CODE: String segment = tokenizer.nextToken(); try { arg0 = translateSegment(segment, instructionSet, file.getName()); } catch (ProgramException pe) { throw new ProgramException("in line " + lineNumber + pe.getMessage()); } arg1 = Short.parseShort(tokenizer.nextToken()); if (arg1 < 0) throw new ProgramException( "in line " + lineNumber + ": Illegal argument - " + line); if (arg0 == HVMInstructionSet.STATIC_SEGMENT_CODE && arg1 > largestStaticIndex) largestStaticIndex = arg1; instructions[pc] = new VMEmulatorInstruction(opCode, arg0, arg1, indexInFunction); break; case HVMInstructionSet.POP_CODE: int n = tokenizer.countTokens(); segment = tokenizer.nextToken(); try { arg0 = translateSegment(segment, instructionSet, file.getName()); } catch (ProgramException pe) { throw new ProgramException("in line " + lineNumber + pe.getMessage()); } arg1 = Short.parseShort(tokenizer.nextToken()); if (arg1 < 0) throw new ProgramException( "in line " + lineNumber + ": Illegal argument - " + line); if (arg0 == HVMInstructionSet.STATIC_SEGMENT_CODE && arg1 > largestStaticIndex) largestStaticIndex = arg1; instructions[pc] = new VMEmulatorInstruction(opCode, arg0, arg1, indexInFunction); break; case HVMInstructionSet.FUNCTION_CODE: currentFunction = tokenizer.nextToken(); indexInFunction = 0; arg0 = Short.parseShort(tokenizer.nextToken()); if (arg0 < 0) throw new ProgramException( "in line " + lineNumber + ": Illegal argument - " + line); instructions[pc] = new VMEmulatorInstruction(opCode, arg0, indexInFunction); instructions[pc].setStringArg(currentFunction); break; case HVMInstructionSet.CALL_CODE: String functionName = tokenizer.nextToken(); try { arg0 = getAddress(functionName); } catch (ProgramException pe) { throw new ProgramException("in line " + lineNumber + ": " + pe.getMessage()); } arg1 = Short.parseShort(tokenizer.nextToken()); if (arg1 < 0 || ((arg0 < 0 || arg0 > Definitions.ROM_SIZE) && arg0 != BUILTIN_FUNCTION_ADDRESS)) throw new ProgramException( "in line " + lineNumber + ": Illegal argument - " + line); instructions[pc] = new VMEmulatorInstruction(opCode, arg0, arg1, indexInFunction); instructions[pc].setStringArg(functionName); break; case HVMInstructionSet.LABEL_CODE: label = currentFunction + "$" + tokenizer.nextToken(); instructions[pc] = new VMEmulatorInstruction(opCode, (short) (-1)); instructions[pc].setStringArg(label); indexInFunction--; // since Label is not a "physical" instruction break; case HVMInstructionSet.GOTO_CODE: label = currentFunction + "$" + tokenizer.nextToken(); Short labelAddress = (Short) symbols.get(label); if (labelAddress == null) throw new ProgramException("in line " + lineNumber + ": Unknown label - " + label); arg0 = labelAddress.shortValue(); if (arg0 < 0 || arg0 > Definitions.ROM_SIZE) throw new ProgramException( "in line " + lineNumber + ": Illegal argument - " + line); instructions[pc] = new VMEmulatorInstruction(opCode, arg0, indexInFunction); instructions[pc].setStringArg(label); break; case HVMInstructionSet.IF_GOTO_CODE: label = currentFunction + "$" + tokenizer.nextToken(); labelAddress = (Short) symbols.get(label); if (labelAddress == null) throw new ProgramException("in line " + lineNumber + ": Unknown label - " + label); arg0 = labelAddress.shortValue(); if (arg0 < 0 || arg0 > Definitions.ROM_SIZE) throw new ProgramException( "in line " + lineNumber + ": Illegal argument - " + line); instructions[pc] = new VMEmulatorInstruction(opCode, arg0, indexInFunction); instructions[pc].setStringArg(label); break; // All other instructions have either 1 or 0 arguments and require no // special treatment default: if (tokenizer.countTokens() == 0) { instructions[pc] = new VMEmulatorInstruction(opCode, indexInFunction); } else { arg0 = Short.parseShort(tokenizer.nextToken()); if (arg0 < 0) throw new ProgramException( "in line " + lineNumber + ": Illegal argument - " + line); instructions[pc] = new VMEmulatorInstruction(opCode, arg0, indexInFunction); } break; } // check end of command if (tokenizer.hasMoreTokens()) throw new ProgramException("in line " + lineNumber + ": Too many arguments - " + line); pc++; indexInFunction++; } nextPC = pc; } reader.close(); } catch (IOException ioe) { throw new ProgramException("Error while reading from file"); } catch (NumberFormatException nfe) { throw new ProgramException("Illegal 16-bit value"); } catch (NoSuchElementException nsee) { throw new ProgramException("In line " + lineNumber + ": unexpected end of command"); } if (isSlashStar) { throw new ProgramException("Unterminated /* comment at end of file"); } }