Example usage for java.util Scanner nextInt

List of usage examples for java.util Scanner nextInt

Introduction

In this page you can find the example usage for java.util Scanner nextInt.

Prototype

public int nextInt() 

Source Link

Document

Scans the next token of the input as an int .

Usage

From source file:xml.sk.Parser.java

/**
 * Parses AgeSk.xml.//w  w w .  j  a v  a2 s . c o m
 *
 * @param manager age manager to store data
 * @throws javax.xml.parsers.ParserConfigurationException
 * @throws org.xml.sax.SAXException
 * @throws java.io.IOException
 */
public void parseAgeSk(AgeManagerImpl manager) throws ParserConfigurationException, SAXException, IOException,
        XPathExpressionException, ParseException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse("src/main/java/xml/sk/AgeSk.xml");

    NodeList educationList = doc.getElementsByTagName("PRAC_strMzdyVek");
    for (int i = 0; i < educationList.getLength(); i++) {
        Element educationNode = (Element) educationList.item(i);

        if (!"EUR".equals(educationNode.getElementsByTagName("MJ").item(0).getTextContent()))
            continue;

        String ageStr = educationNode.getElementsByTagName("UKAZ2").item(0).getTextContent();
        Scanner in = new Scanner(ageStr).useDelimiter("[^0-9]+");
        Integer age1 = in.nextInt();
        Integer age2 = null;
        if (in.hasNext())
            age2 = in.nextInt();

        String sex = educationNode.getElementsByTagName("UKAZ1").item(0).getTextContent();
        String[] splited = sex.split(" ");
        sex = splited[splited.length - 1];

        NodeList years = educationNode.getChildNodes();

        for (int j = 0; j < years.getLength(); j++) {
            if (years.item(j).getNodeType() == Node.TEXT_NODE) {
                continue;
            }
            Element yearNode = (Element) years.item(j);
            if ("MJ".equals(yearNode.getNodeName()) || "UKAZ".equals(yearNode.getNodeName().substring(0, 4)))
                continue;

            String year = yearNode.getNodeName().substring(1);
            if (".".equals(yearNode.getTextContent()) || "".equals(yearNode.getTextContent())) {
                continue;
            }
            String salaryStr = yearNode.getTextContent().replaceAll(" ", "");
            NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
            Number number = format.parse(salaryStr);
            double salaryDouble = number.doubleValue();

            Age age = new Age();

            if (age2 == null) {
                if (age1 == 19) {
                    age1 = 0;
                    age2 = 19;
                }
                if (age1 == 60)
                    age2 = 99;
            }
            age.setAgeFrom(age1);
            age.setAgeTo(age2);
            age.setCountry("sk");
            age.setYear(year);
            age.setAverageSalary(salaryDouble);
            if (!"spolu".equals(sex))
                age.setSex(sex);

            manager.createAge(age);
        }
    }
}

From source file:br.edu.ifes.bd2dao.cgt.Menu.java

private Disciplina buscarDisciplinaPorId() {
    Scanner scanId = new Scanner(System.in);
    System.out.println("Infome o id do elemento desejado: ");
    int id = scanId.nextInt();
    return new Disciplina().selecionar(new Long(id));
}

From source file:br.edu.ifes.bd2dao.cgt.Menu.java

private void atualizarAluno() {
    Scanner sc = new Scanner(System.in);

    listarAlunos();// ww  w. ja  va 2 s  .  co  m

    System.out.println("\nInforme um ID:");
    int id = sc.nextInt();

    Aluno a = new Aluno().selecionar(new Long(id));

    Field fields[] = Aluno.class.getDeclaredFields();
    for (Field field : fields) {
        if (!field.getName().equals("id")) {
            System.out.println("Deseja atualizar o campo (" + field.getName().toUpperCase() + ") [n/s]?");
            String opt = sc.next().toUpperCase();
            if (opt.contains("S")) {
                setValue(field.getName(), a);
            }
        }
    }

    try {
        a.atualizar(a);
    } catch (IdNotFoundException ex) {
        ex.printStackTrace();
    }
}

From source file:br.edu.ifes.bd2dao.cgt.Menu.java

private Aluno buscarAlunoPorId() {
    Scanner scanId = new Scanner(System.in);
    listar(buscarAlunos());/*  ww  w  .  j a  v a  2 s .  c  om*/
    System.out.println("Infome o id do elemento desejado: ");
    int id = scanId.nextInt();
    return new Aluno().selecionar(new Long(id));
}

From source file:CourseFileManagementSystem.Upload.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.write("<html><head></head><body>");
    // Check that we have a file upload request
    if (!ServletFileUpload.isMultipartContent(request)) {
        // if not, we stop here
        PrintWriter writer = response.getWriter();
        writer.println("Error: Form must has enctype=multipart/form-data.");
        writer.flush();//w  w w . j av  a 2 s. c  o  m
        return;
    }

    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // Sets the size threshold beyond which files are written directly to
    // disk.
    factory.setSizeThreshold(MAX_MEMORY_SIZE);

    // Sets the directory used to temporarily store files that are larger
    // than the configured size threshold. We use temporary directory for
    // java
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    // constructs the folder where uploaded file will be stored
    String temp_folder = " ";
    try {
        String dataFolder = getServletContext().getRealPath("") + File.separator + DATA_DIRECTORY;
        temp_folder = dataFolder;
        File uploadD = new File(dataFolder);
        if (!uploadD.exists()) {
            uploadD.mkdir();
        }

        ResultList rs5 = DB.query(
                "SELECT * FROM course AS c, section AS s, year_semester AS ys, upload_checklist AS uc WHERE s.courseCode = c.courseCode "
                        + "AND s.semesterID = ys.semesterID AND s.courseID = c.courseID AND s.sectionID="
                        + sectionID);
        rs5.next();

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Sets maximum size of upload file
        upload.setFileSizeMax(MAX_FILE_SIZE);

        // Set overall request size constraint
        upload.setSizeMax(MAX_REQUEST_SIZE);

        // creates the directory if it does not exist
        String path1 = getServletContext().getContextPath() + "/" + DATA_DIRECTORY + "/";
        String temp_semester = rs5.getString("year") + "-" + rs5.getString("semester");
        String real_path = temp_folder + File.separator + temp_semester;
        File semester = new File(real_path);

        if (!semester.exists()) {
            semester.mkdir();
        }
        path1 += temp_semester + "/";
        real_path += File.separator;

        String temp_course = rs5.getString("courseCode") + rs5.getString("courseID") + "-"
                + rs5.getString("courseName");
        String real_path1 = real_path + temp_course;
        File course = new File(real_path1);
        if (!course.exists()) {
            course.mkdir();
        }
        path1 += temp_course + "/";
        real_path1 += File.separator;

        String temp_section = "section-" + rs5.getString("sectionNo");
        String real_path2 = real_path1 + temp_section;
        File section = new File(real_path2);
        if (!section.exists()) {
            section.mkdir();
        }
        path1 += temp_section + "/";
        real_path2 += File.separator;
        String sectionPath = path1;

        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        if (items != null && items.size() > 0) {
            // iterates over form's fields
            for (FileItem item : items) {
                // processes only fields that are not form fields
                if (!item.isFormField() && !item.getName().equals("")) {
                    String DBPath = "";
                    System.out.println(item.getName() + " file is for " + item.getFieldName());
                    Scanner field_name = new Scanner(item.getFieldName()).useDelimiter("[^0-9]+");
                    int id = field_name.nextInt();
                    fileName = new File(item.getName()).getName();
                    ResultList rs = DB.query("SELECT * FROM upload_checklist WHERE checklistID =" + id);
                    rs.next();
                    String temp_file = rs.getString("label");
                    String real_path3 = real_path2 + temp_file;
                    File file_type = new File(real_path3);
                    if (!file_type.exists())
                        file_type.mkdir();
                    DBPath = sectionPath + "/" + temp_file + "/";
                    String context_path = DBPath;
                    real_path3 += File.separator;
                    String filePath = real_path3 + fileName;
                    DBPath += fileName;
                    String temp_DBPath = DBPath;

                    int count = 0;
                    File f = new File(filePath);
                    String temp_fileName = f.getName();
                    String fileNameWithOutExt = FilenameUtils.removeExtension(temp_fileName);
                    String extension = FilenameUtils.getExtension(filePath);
                    String newFullPath = filePath;
                    String tempFileName = " ";

                    while (f.exists()) {
                        ++count;
                        tempFileName = fileNameWithOutExt + "_(" + count + ").";
                        newFullPath = real_path3 + tempFileName + extension;
                        temp_DBPath = context_path + tempFileName + extension;
                        f = new File(newFullPath);
                    }

                    filePath = newFullPath;
                    System.out.println("New path: " + filePath);
                    DBPath = temp_DBPath;
                    String changeFilePath = filePath.replace('/', '\\');
                    String changeFilePath1 = changeFilePath.replace("Course_File_Management_System\\", "");
                    File uploadedFile = new File(changeFilePath1);
                    System.out.println("Change filepath = " + changeFilePath1);
                    System.out.println("DBPath = " + DBPath);
                    // saves the file to upload directory
                    item.write(uploadedFile);
                    String query = "INSERT INTO files (fileDirectory) values('" + DBPath + "')";
                    DB.update(query);
                    ResultList rs3 = DB.query("SELECT label FROM upload_checklist WHERE id=" + id);
                    while (rs3.next()) {
                        String label = rs3.getString("label");
                        out.write("<a href=\"Upload?fileName=" + changeFilePath1 + "\">Download " + label
                                + "</a>");
                        out.write("<br><br>");
                    }
                    ResultList rs4 = DB.query("SELECT * FROM files ORDER BY fileID DESC LIMIT 1");
                    rs4.next();
                    String query2 = "INSERT INTO lecturer_upload (fileID, sectionID, checklistID) values("
                            + rs4.getString("fileID") + ", " + sectionID + ", " + id + ")";
                    DB.update(query2);
                }
            }
        }
    } catch (FileUploadException ex) {
        throw new ServletException(ex);
    } catch (Exception ex) {
        throw new ServletException(ex);
    }
    response.sendRedirect(request.getHeader("Referer"));
}

From source file:fr.vdl.android.holocolors.HoloColorsDialog.java

private void checkLicence() {
    try {/*from ww  w.j a v a  2  s .c  om*/
        String userHome = System.getProperty("user.home");
        File holoColorsFolder = new File(userHome + File.separator + ".holocolors");
        File licenceFile = new File(holoColorsFolder, ".licence");
        File noDonationFile = new File(holoColorsFolder, ".nodonation");

        if (noDonationFile.exists()) {
            return;
        }

        int usage = 1;
        boolean showPopup = false;
        if (!holoColorsFolder.exists()) {
            holoColorsFolder.mkdir();
            showPopup = true;
            licenceFile.createNewFile();
        } else {
            Scanner in = new Scanner(new FileReader(licenceFile));
            if (in.hasNextInt()) {
                usage = in.nextInt() + 1;
            }
            in.close();
        }
        if (usage > 10) {
            usage = 1;
            showPopup = true;
        }
        Writer out = new BufferedWriter(new FileWriter(licenceFile));
        out.write(String.valueOf(usage));
        out.close();

        if (showPopup) {
            Object[] donationOption = { "Make a donation", "Maybe later", "No Never" };
            int option = JOptionPane.showOptionDialog(ahcPanel,
                    "Thanks for using Android Holo Colors!\n\nAndroid Holo Colors (website and plugin) is free to use.\nIf you save time and money with it, please make a donation.",
                    "Support Android Holo Colors", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
                    new ImageIcon(getClass().getResource("/icons/H64.png")), donationOption, donationOption[0]);
            if (option == 0) {
                openWebpage(
                        "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=XQSBX55A2Z46U");
            }
            if (option == 2) {
                noDonationFile.createNewFile();
            }
        }
    } catch (Exception e) {
        // no matter, nothing to do
        e.printStackTrace();
    }
}

From source file:cz.cuni.mff.ksi.jinfer.autoeditor.BububuEditor.java

/**
 * Draws automaton and waits until user picks two states and clicks
 * 'continue' button.//from www .j  a  v  a  2s . c o m
 *
 * @param automaton automaton to be drawn
 * @return if user picks exactly two states returns Pair of them otherwise null
 */
@Override
public List<State<T>> drawAutomatonToPickStates(final Automaton<T> automaton) {

    final DirectedSparseMultigraph<State<T>, Step<T>> graph = new DirectedSparseMultigraph<State<T>, Step<T>>();
    final Map<State<T>, Set<Step<T>>> automatonDelta = automaton.getDelta();

    // Get vertices = states of automaton
    for (Entry<State<T>, Set<Step<T>>> entry : automatonDelta.entrySet()) {
        graph.addVertex(entry.getKey());
    }

    // Get edges of automaton
    for (Entry<State<T>, Set<Step<T>>> entry : automatonDelta.entrySet()) {
        for (Step<T> step : entry.getValue()) {
            graph.addEdge(step, step.getSource(), step.getDestination());
        }
    }

    Map<State<T>, Point2D> positions = new HashMap<State<T>, Point2D>();

    ProcessBuilder p = new ProcessBuilder(Arrays.asList("/usr/bin/dot", "-Tplain"));
    try {
        Process k = p.start();
        k.getOutputStream().write((new AutomatonToDot<T>()).convertToDot(automaton, symbolToString).getBytes());
        k.getOutputStream().flush();
        BufferedReader b = new BufferedReader(new InputStreamReader(k.getInputStream()));
        k.getOutputStream().close();

        Scanner s = new Scanner(b);
        s.next();
        s.next();
        double width = s.nextDouble();
        double height = s.nextDouble();
        double windowW = 500;
        double windowH = 300;

        while (s.hasNext()) {
            if (s.next().equals("node")) {
                int nodeName = s.nextInt();
                double x = s.nextDouble();
                double y = s.nextDouble();
                for (State<T> state : automatonDelta.keySet()) {
                    if (state.getName() == nodeName) {
                        positions.put(state,
                                new Point((int) (windowW * x / width), (int) (windowH * y / height)));
                        break;
                    }
                }
            }
        }
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
    Transformer<State<T>, Point2D> trans = TransformerUtils.mapTransformer(positions);

    // TODO rio find suitable layout
    final Layout<State<T>, Step<T>> layout = new StaticLayout<State<T>, Step<T>>(graph, trans);

    //layout.setSize(new Dimension(300,300)); // sets the initial size of the space

    visualizationViewer = new VisualizationViewer<State<T>, Step<T>>(layout);
    //visualizationViewer.setPreferredSize(new Dimension(350,350)); //Sets the viewing area size

    visualizationViewer.getRenderContext().setVertexLabelTransformer(new ToStringLabeller<State<T>>());
    visualizationViewer.getRenderContext().setEdgeLabelTransformer(new Transformer<Step<T>, String>() {
        @Override
        public String transform(Step<T> i) {
            return BububuEditor.this.symbolToString.toString(i.getAcceptSymbol());
        }
    });

    final PluggableGraphMouse gm = new PluggableGraphMouse();
    gm.add(new PickingUnlimitedGraphMousePlugin<State<T>, Step<T>>());
    visualizationViewer.setGraphMouse(gm);

    // Call GUI in a special thread. Required by NB.
    synchronized (this) {
        WindowManager.getDefault().invokeWhenUIReady(new Runnable() {

            @Override
            public void run() {
                // Pass this as argument so the thread will be able to wake us up.
                AutoEditorTopComponent.findInstance().drawAutomatonBasicVisualizationServer(BububuEditor.this,
                        visualizationViewer, "Please select two states to be merged together.");
            }
        });

        try {
            // Sleep on this.
            this.wait();
        } catch (InterruptedException e) {
            return null;
        }
    }

    /* AutoEditorTopComponent wakes us up. Get the result and return it.
     * VisualizationViewer should give us the information about picked vertices.
     */
    final Set<State<T>> pickedSet = visualizationViewer.getPickedVertexState().getPicked();
    List<State<T>> lst = new ArrayList<State<T>>(pickedSet);
    return lst;
}

From source file:de.bley.word.menu.Menue.java

/**
 * Komponenten des Programms werden geladen.
 *///w  w w. j  ava2  s  .c o  m
protected void showFiles(Scanner scan) {
    final ArrayList<String> files = zuordnung.getReader().showFiles(zuordnung.getPath().getFiledirectory());
    int counter = 0;

    zuordnung.getEingabe().showFile();
    if (files != null) {
        for (String file : files) {
            zuordnung.getAusgabe().ausgeben(counter + " = " + file);
            counter++;
        }
        boolean run;
        if (counter > 0) {
            run = true;
        } else {
            run = false;
        }
        while (run) {
            final int input = scan.nextInt();
            if (input <= files.size() - 1) {
                zuordnung.getPath().setFilename(files.get(input));
                run = false;

            } else {
                System.out.println("Falsche Eingabe");
                run = false;

            }
        }
    }
}

From source file:com.flexive.faces.beans.QueryEditorBean.java

private void joinSelectedNodes(QueryOperatorNode.Operator operator) {
    Scanner scanner = new Scanner(nodeSelection).useDelimiter(",");
    List<Integer> nodeIds = new ArrayList<Integer>();
    while (scanner.hasNextInt()) {
        nodeIds.add(scanner.nextInt());
    }/*from   w w  w . j av  a 2 s  . c  o  m*/
    if (nodeIds.size() > 1) {
        getRootNode().joinNodes(nodeIds, operator);
    }
    FxJsf1Utils.resetFaceletsComponent(RESET_COMPONENT_ID);
    updateQueryStore();
}

From source file:com.anuta.internal.YangHelperMojo.java

private double versionCompare(String version1, String version2) {
    Scanner v1Scanner = new Scanner(version1);
    Scanner v2Scanner = new Scanner(version2);
    v1Scanner.useDelimiter("\\.");
    v2Scanner.useDelimiter("\\.");

    while (v1Scanner.hasNextInt() && v2Scanner.hasNextInt()) {
        int v1 = v1Scanner.nextInt();
        int v2 = v2Scanner.nextInt();
        if (v1 < v2) {
            return -1;
        } else if (v1 > v2) {
            return 1;
        }//from  ww w  .  j  ava 2  s. c  o m
    }

    if (v1Scanner.hasNextInt()) {
        return 1;
    } else if (v2Scanner.hasNextInt()) {
        return -1;
    } else {
        return 0;
    }
}