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:math2605.gn_qua.java

/**
 * @param args the command line arguments
 *///from  www .jav a  2s  .c  o m
public static void main(String[] args) {
    //get file name
    System.out.println("Please enter a file name:");
    Scanner scanner = new Scanner(System.in);
    String fileName = scanner.nextLine();
    List<String[]> pairs = new ArrayList<>();
    //get coordinate pairs and add to arraylist
    try {
        BufferedReader br = new BufferedReader(new FileReader(fileName));
        String line;
        while ((line = br.readLine()) != null) {
            String[] pair = line.split(",");
            pairs.add(pair);
        }
        br.close();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

    System.out.println("Please enter the value of a:");
    double a = scanner.nextInt();
    System.out.println("Please enter the value of b:");
    double b = scanner.nextInt();
    System.out.println("Please enter the value of c:");
    double c = scanner.nextInt();
    //init B, vector with 3 coordinates
    RealMatrix B = new Array2DRowRealMatrix(3, 1);
    B.setEntry(0, 0, a);
    B.setEntry(1, 0, b);
    B.setEntry(2, 0, c);

    System.out.println("Please enter the number of iteration for the Gauss-newton:");
    //init N, number of iterations
    int N = scanner.nextInt();

    //init r, vector of residuals
    RealMatrix r = new Array2DRowRealMatrix(pairs.size(), 1);
    setR(pairs, a, b, c, r);

    //init J, Jacobian of r
    RealMatrix J = new Array2DRowRealMatrix(pairs.size(), 3);
    setJ(pairs, a, b, c, r, J);

    System.out.println("J");
    System.out.println(J);
    System.out.println("r");
    System.out.println(r);

    RealMatrix sub = findQR(J, r);

    for (int i = N; i > 0; i--) {
        B = B.subtract(sub);
        double B0 = B.getEntry(0, 0);
        double B1 = B.getEntry(1, 0);
        double B2 = B.getEntry(2, 0);
        //CHANGE ABC TO USE B0, B1, B2
        setR(pairs, B0, B1, B2, r);
        setJ(pairs, B0, B1, B2, r, J);
    }
    System.out.println("B");
    System.out.println(B.toString());
}

From source file:aula1.Aula1.java

/**
 * @param args the command line arguments
 *//*from w  ww.  j av  a2s.c  om*/
public static void main(String[] args) {
    Scanner dados = new Scanner(System.in);
    int escolha;
    double ini;
    double fim;
    String exp;
    String info;
    int sens = 0;
    boolean valida = true;

    do {
        System.out.println(
                "Decida a operao: 0 para montar grfico, 1 para calcular limite, 2 para calcular qualquer expresso");
        escolha = dados.nextInt();
        switch (escolha) {
        case 0:
            System.out.println("Informe o inicio do dominio");
            ini = dados.nextDouble();
            System.out.println("Informe o fim do dominio");
            fim = dados.nextDouble();
            System.out.println("Informe a quantidade de casas decimais desejadas: ");
            sens = dados.nextInt();
            System.out.println("Informe a expresso: ");
            exp = dados.next();
            double[] x = montaDominio(ini, fim, sens);
            calcula(x, exp);
            valida = false;
            break;
        case 1:
            System.out.println("Informe a expresso: ");
            exp = dados.next();
            System.out.println("Informe o ponto limite: ");
            info = dados.next();
            try {
                calculaLimite(exp, info);
            } catch (Exception ex) {
                System.out
                        .println("Erro: " + ex.getMessage() + "Tentativade aplcao do teorema do confronto");

            }
            valida = false;
            break;
        case 2:
            System.out.println("Informe a expresso:");
            info = dados.next();
            try {
                System.out.println(conversor(info, "0"));
            } catch (Exception ex) {
                System.out.println("Erro: " + ex.getMessage());
            }
            valida = false;
            break;
        default:
            System.out.println("Escolha invlida!");
            break;
        }
    } while (valida);

    //        Double[] vet = new Double[3];         
    //        vet = lerDados();
    //        montaDominio(vet[0], vet[1], vet[2].intValue());
    //        calculaLimite(3);
}

From source file:gash.router.app.DemoApp.java

/**
 * sample application (client) use of our messaging service
 *
 * @param args/*from   w w  w.j  a va 2  s  .  c o m*/
 */
public static void main(String[] args) {
    if (args.length == 0) {
        System.out.println("usage:  <ip address> <port no>");
        System.exit(1);
    }
    String ipAddress = args[0];
    int port = Integer.parseInt(args[1]);
    Scanner s = new Scanner(System.in);
    boolean isExit = false;
    try {
        MessageClient mc = new MessageClient(ipAddress, port);
        DemoApp da = new DemoApp(mc);
        int choice = 0;

        while (true) {
            System.out.println(
                    "Enter your option \n1. WRITE a file. \n2. READ a file. \n3. Update a File. \n4. Delete a File\n 5 Ping(Global)\n 6 Exit");
            choice = s.nextInt();
            switch (choice) {
            case 1: {
                System.out.println("Enter the full pathname of the file to be written ");
                String currFileName = s.next();
                File file = new File(currFileName);
                if (file.exists()) {
                    ArrayList<ByteString> chunkedFile = da.divideFileChunks(file);
                    String name = file.getName();
                    int i = 0;
                    String requestId = SupportMessageGenerator.generateRequestID();
                    for (ByteString string : chunkedFile) {
                        mc.saveFile(name, string, chunkedFile.size(), i++, requestId);
                    }
                } else {
                    throw new FileNotFoundException("File does not exist in this path ");
                }
            }
                break;
            case 2: {
                System.out.println("Enter the file name to be read : ");
                String currFileName = s.next();
                da.sendReadTasks(currFileName);
                //Thread.sleep(1000 * 100);
            }
                break;
            case 3: {
                System.out.println("Enter the full pathname of the file to be updated");
                String currFileName = s.next();
                File file = new File(currFileName);
                if (file.exists()) {
                    ArrayList<ByteString> chunkedFile = da.divideFileChunks(file);
                    String name = file.getName();
                    int i = 0;
                    String requestId = SupportMessageGenerator.generateRequestID();
                    for (ByteString string : chunkedFile) {
                        mc.updateFile(name, string, chunkedFile.size(), i++, requestId);
                    }
                    //Thread.sleep(10 * 1000);
                } else {
                    throw new FileNotFoundException("File does not exist in this path ");
                }
            }
                break;

            case 4:
                System.out.println("Enter the file name to be deleted : ");
                String currFileName = s.next();
                mc.deleteFile(currFileName);
                //Thread.sleep(1000 * 100);
                break;
            case 5:
                da.ping(1);
                break;
            case 6:
                isExit = true;
                break;
            default:
                break;
            }
            if (isExit)
                break;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        CommConnection.getInstance().release();
        if (s != null)
            s.close();
    }
}

From source file:com.bright.json.JSonRequestor.java

public static void main(String[] args) {
    String fileBasename = null;/*from   ww w  .j av a2 s .  c o m*/
    String[] zipArgs = null;
    JFileChooser chooser = new JFileChooser("/Users/panos/STR_GRID");
    try {

        chooser.setCurrentDirectory(new java.io.File("."));
        chooser.setDialogTitle("Select the input directory");

        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        chooser.setAcceptAllFileFilterUsed(false);

        if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
            System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory());
            System.out.println("getSelectedFile() : " + chooser.getSelectedFile());

            // String fileBasename =
            // chooser.getSelectedFile().toString().substring(chooser.getSelectedFile().toString().lastIndexOf(File.separator)+1,chooser.getSelectedFile().toString().lastIndexOf("."));
            fileBasename = chooser.getSelectedFile().toString()
                    .substring(chooser.getSelectedFile().toString().lastIndexOf(File.separator) + 1);
            System.out.println("Base name: " + fileBasename);

            zipArgs = new String[] { chooser.getSelectedFile().toString(),
                    chooser.getCurrentDirectory().toString() + File.separator + fileBasename + ".zip" };
            com.bright.utils.ZipFile.main(zipArgs);

        } else {
            System.out.println("No Selection ");

        }
    } catch (Exception e) {

        System.out.println(e.toString());

    }

    JTextField uiHost = new JTextField("ucs-head.brightcomputing.com");
    // TextPrompt puiHost = new
    // TextPrompt("hadoop.brightcomputing.com",uiHost);
    JTextField uiUser = new JTextField("nexus");
    // TextPrompt puiUser = new TextPrompt("nexus", uiUser);
    JTextField uiPass = new JPasswordField("system");
    // TextPrompt puiPass = new TextPrompt("", uiPass);
    JTextField uiWdir = new JTextField("/home/nexus/pp1234");
    // TextPrompt puiWdir = new TextPrompt("/home/nexus/nexus_workdir",
    // uiWdir);
    JTextField uiOut = new JTextField("foo");
    // TextPrompt puiOut = new TextPrompt("foobar123", uiOut);

    JPanel myPanel = new JPanel(new GridLayout(5, 1));
    myPanel.add(new JLabel("Bright HeadNode hostname:"));
    myPanel.add(uiHost);
    // myPanel.add(Box.createHorizontalStrut(1)); // a spacer
    myPanel.add(new JLabel("Username:"));
    myPanel.add(uiUser);
    myPanel.add(new JLabel("Password:"));
    myPanel.add(uiPass);
    myPanel.add(new JLabel("Working Directory:"));
    myPanel.add(uiWdir);
    // myPanel.add(Box.createHorizontalStrut(1)); // a spacer
    myPanel.add(new JLabel("Output Study Name ( -s ):"));
    myPanel.add(uiOut);

    int result = JOptionPane.showConfirmDialog(null, myPanel, "Please fill in all the fields.",
            JOptionPane.OK_CANCEL_OPTION);
    if (result == JOptionPane.OK_OPTION) {
        System.out.println("Input received.");

    }

    String rfile = uiWdir.getText();
    String rhost = uiHost.getText();
    String ruser = uiUser.getText();
    String rpass = uiPass.getText();
    String nexusOut = uiOut.getText();

    String[] myarg = new String[] { zipArgs[1], ruser + "@" + rhost + ":" + rfile, nexusOut, fileBasename };
    com.bright.utils.ScpTo.main(myarg);

    String cmURL = "https://" + rhost + ":8081/json";
    List<Cookie> cookies = doLogin(ruser, rpass, cmURL);
    chkVersion(cmURL, cookies);

    jobSubmit myjob = new jobSubmit();
    jobSubmit.jobObject myjobObj = new jobSubmit.jobObject();

    myjob.setService("cmjob");
    myjob.setCall("submitJob");

    myjobObj.setQueue("defq");
    myjobObj.setJobname("myNexusJob");
    myjobObj.setAccount(ruser);
    myjobObj.setRundirectory(rfile);
    myjobObj.setUsername(ruser);
    myjobObj.setGroupname("cmsupport");
    myjobObj.setPriority("1");
    myjobObj.setStdinfile(rfile + "/stdin-mpi");
    myjobObj.setStdoutfile(rfile + "/stdout-mpi");
    myjobObj.setStderrfile(rfile + "/stderr-mpi");
    myjobObj.setResourceList(Arrays.asList(""));
    myjobObj.setDependencies(Arrays.asList(""));
    myjobObj.setMailNotify(false);
    myjobObj.setMailOptions("ALL");
    myjobObj.setMaxWallClock("00:10:00");
    myjobObj.setNumberOfProcesses(1);
    myjobObj.setNumberOfNodes(1);
    myjobObj.setNodes(Arrays.asList(""));
    myjobObj.setCommandLineInterpreter("/bin/bash");
    myjobObj.setUserdefined(Arrays.asList("cd " + rfile, "date", "pwd"));
    myjobObj.setExecutable("mpirun");
    myjobObj.setArguments("-env I_MPI_FABRICS shm:tcp " + Constants.NEXUSSIM_EXEC + " -mpi -c " + rfile + "/"
            + fileBasename + "/" + fileBasename + " -s " + rfile + "/" + fileBasename + "/" + nexusOut);
    myjobObj.setModules(Arrays.asList("shared", "nexus", "intel-mpi/64"));
    myjobObj.setDebug(false);
    myjobObj.setBaseType("Job");
    myjobObj.setIsSlurm(true);
    myjobObj.setUniqueKey(0);
    myjobObj.setModified(false);
    myjobObj.setToBeRemoved(false);
    myjobObj.setChildType("SlurmJob");
    myjobObj.setJobID("Nexus test");

    // Map<String,jobSubmit.jobObject > mymap= new HashMap<String,
    // jobSubmit.jobObject>();
    // mymap.put("Slurm",myjobObj);
    ArrayList<Object> mylist = new ArrayList<Object>();
    mylist.add("slurm");
    mylist.add(myjobObj);
    myjob.setArgs(mylist);

    GsonBuilder builder = new GsonBuilder();
    builder.enableComplexMapKeySerialization();

    // Gson g = new Gson();
    Gson g = builder.create();

    String json2 = g.toJson(myjob);

    // To be used from a real console and not Eclipse
    Delete.main(zipArgs[1]);
    String message = JSonRequestor.doRequest(json2, cmURL, cookies);
    @SuppressWarnings("resource")
    Scanner resInt = new Scanner(message).useDelimiter("[^0-9]+");
    int jobID = resInt.nextInt();
    System.out.println("Job ID: " + jobID);

    JOptionPane optionPane = new JOptionPane(message);
    JDialog myDialog = optionPane.createDialog(null, "CMDaemon response: ");
    myDialog.setModal(false);
    myDialog.setVisible(true);

    ArrayList<Object> mylist2 = new ArrayList<Object>();
    mylist2.add("slurm");
    String JobID = Integer.toString(jobID);
    mylist2.add(JobID);
    myjob.setArgs(mylist2);
    myjob.setService("cmjob");
    myjob.setCall("getJob");
    String json3 = g.toJson(myjob);
    System.out.println("JSON Request No. 4 " + json3);

    cmReadFile readfile = new cmReadFile();
    readfile.setService("cmmain");
    readfile.setCall("readFile");
    readfile.setUserName(ruser);

    int fileByteIdx = 1;

    readfile.setPath(rfile + "/" + fileBasename + "/" + fileBasename + ".sum@+" + fileByteIdx);
    String json4 = g.toJson(readfile);

    String monFile = JSonRequestor.doRequest(json4, cmURL, cookies).replaceAll("^\"|\"$", "");
    if (monFile.startsWith("Unable")) {
        monFile = "";
    } else {
        fileByteIdx += countLines(monFile, "\\\\n");
        System.out.println("");
    }

    StringBuffer output = new StringBuffer();
    // Get the correct Line Separator for the OS (CRLF or LF)
    String nl = System.getProperty("line.separator");
    String filename = chooser.getCurrentDirectory().toString() + File.separator + fileBasename + ".sum.txt";
    System.out.println("Local monitoring file: " + filename);

    output.append(monFile.replaceAll("\\\\n", System.getProperty("line.separator")));

    String getJobJSON = JSonRequestor.doRequest(json3, cmURL, cookies);
    jobGet getJobObj = new Gson().fromJson(getJobJSON, jobGet.class);
    System.out.println("Job " + jobID + " status: " + getJobObj.getStatus().toString());

    while (getJobObj.getStatus().toString().equals("RUNNING")
            || getJobObj.getStatus().toString().equals("COMPLETING")) {
        try {

            getJobJSON = JSonRequestor.doRequest(json3, cmURL, cookies);
            getJobObj = new Gson().fromJson(getJobJSON, jobGet.class);
            System.out.println("Job " + jobID + " status: " + getJobObj.getStatus().toString());

            readfile.setPath(rfile + "/" + fileBasename + "/" + fileBasename + ".sum@+" + fileByteIdx);
            json4 = g.toJson(readfile);
            monFile = JSonRequestor.doRequest(json4, cmURL, cookies).replaceAll("^\"|\"$", "");
            if (monFile.startsWith("Unable")) {
                monFile = "";
            } else {

                output.append(monFile.replaceAll("\\\\n", System.getProperty("line.separator")));
                System.out.println("FILE INDEX:" + fileByteIdx);
                fileByteIdx += countLines(monFile, "\\\\n");
            }
            Thread.sleep(Constants.STATUS_CHECK_INTERVAL);
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
        }

    }

    Gson gson_nice = new GsonBuilder().setPrettyPrinting().create();
    String json_out = gson_nice.toJson(getJobJSON);
    System.out.println(json_out);
    System.out.println("JSON Request No. 5 " + json4);

    readfile.setPath(rfile + "/" + fileBasename + "/" + fileBasename + ".sum@+" + fileByteIdx);
    json4 = g.toJson(readfile);
    monFile = JSonRequestor.doRequest(json4, cmURL, cookies).replaceAll("^\"|\"$", "");
    if (monFile.startsWith("Unable")) {
        monFile = "";
    } else {

        output.append(monFile.replaceAll("\\\\n", System.getProperty("line.separator")));
        fileByteIdx += countLines(monFile, "\\\\n");
    }
    System.out.println("FILE INDEX:" + fileByteIdx);

    /*
     * System.out.print("Monitoring file: " + monFile.replaceAll("\\n",
     * System.getProperty("line.separator"))); try {
     * FileUtils.writeStringToFile( new
     * File(chooser.getCurrentDirectory().toString() + File.separator +
     * fileBasename + ".sum.txt"), monFile.replaceAll("\\n",
     * System.getProperty("line.separator"))); } catch (IOException e) {
     * 
     * e.printStackTrace(); }
     */

    if (getJobObj.getStatus().toString().equals("COMPLETED")) {
        String[] zipArgs_from = new String[] { chooser.getSelectedFile().toString(),
                chooser.getCurrentDirectory().toString() + File.separator + fileBasename + "_out.zip" };
        String[] myarg_from = new String[] {
                ruser + "@" + rhost + ":" + rfile + "/" + fileBasename + "_out.zip", zipArgs_from[1], rfile,
                fileBasename };
        com.bright.utils.ScpFrom.main(myarg_from);

        JOptionPane optionPaneS = new JOptionPane("Job execution completed without errors!");
        JDialog myDialogS = optionPaneS.createDialog(null, "Job status: ");
        myDialogS.setModal(false);
        myDialogS.setVisible(true);

    } else {
        JOptionPane optionPaneF = new JOptionPane("Job execution FAILED!");
        JDialog myDialogF = optionPaneF.createDialog(null, "Job status: ");
        myDialogF.setModal(false);
        myDialogF.setVisible(true);
    }

    try {
        System.out.println("Local monitoring file: " + filename);

        BufferedWriter out = new BufferedWriter(new FileWriter(filename));
        String outText = output.toString();
        String newString = outText.replace("\\\\n", nl);

        System.out.println("Text: " + outText);
        out.write(newString);

        out.close();
        rmDuplicateLines.main(filename);
    } catch (IOException e) {
        e.printStackTrace();
    }
    doLogout(cmURL, cookies);
    System.exit(0);
}

From source file:driver.ieSystem2.java

public static void main(String[] args) throws SQLException {

    Scanner sc = new Scanner(System.in);
    boolean login = false;
    int check = 0;
    int id = 0;/*w w w .j a v  a 2 s.  c  om*/
    String user = "";
    String pass = "";
    Person person = null;
    Date day = null;

    JOptionPane.showMessageDialog(null, "WELCOME TO SYSTEM", "Starting Project",
            JOptionPane.INFORMATION_MESSAGE);
    do {
        System.out.println("What do you want?");
        System.out.println("press 1 : Login");
        System.out.println("press 2 : Create New User");
        System.out.println("Press 3 : Exit ");
        System.out.println("");
        do {
            try {
                System.out.print("Enter: ");
                check = sc.nextInt();
            } catch (InputMismatchException e) {
                JOptionPane.showMessageDialog(null, "Invalid Input", "Message", JOptionPane.WARNING_MESSAGE);
                sc.next();
            }
        } while (check <= 1 && check >= 3);

        // EXIT 
        if (check == 3) {
            System.out.println("Close Application");
            System.exit(0);
        }
        // CREATE USER
        if (check == 2) {
            System.out.println("-----------------------------------------");
            System.out.println("Create New User");
            System.out.println("-----------------------------------------");
            System.out.print("Account ID: ");
            id = sc.nextInt();
            System.out.print("Username: ");
            user = sc.next();
            System.out.print("Password: ");
            pass = sc.next();
            try {
                Person.createUser(id, user, pass, 0, 0, 0, 0, 0);
                System.out.println("-----------------------------------------");
                System.out.println("Create Complete");
                System.out.println("-----------------------------------------");
            } catch (Exception e) {
                System.out.println("-----------------------------------------");
                System.out.println("Error, Try again");
                System.out.println("-----------------------------------------");
            }
        } else if (check == 1) {
            // LOGIN
            do {
                System.out.println("-----------------------------------------");
                System.out.println("LOGIN ");
                System.out.print("Username: ");
                user = sc.next();
                System.out.print("Password: ");
                pass = sc.next();
                if (Person.checkUser(user, pass)) {
                    System.out.println("-----------------------------------------");
                    System.out.println("Login Complete");
                } else {
                    System.out.println("-----------------------------------------");
                    System.out.println("Invalid Username / Password");
                }
            } while (!Person.checkUser(user, pass));
        }
    } while (check != 1);
    login = true;

    person = new Person(user);
    do {
        System.out.println("-----------------------------------------");
        System.out.println("Hi " + person.getPerName());
        System.out.println("Press 1 : Add Income");
        System.out.println("Press 2 : Add Expense");
        System.out.println("Press 3 : Add Save");
        System.out.println("Press 4 : History");
        System.out.println("Press 5 : Search");
        System.out.println("Press 6 : Analytics");
        System.out.println("Press 7 : Total");
        System.out.println("Press 8 : All Summary");
        System.out.println("Press 9 : Sign Out");
        do {
            try {
                System.out.print("Enter : ");
                check = sc.nextInt();
            } catch (InputMismatchException e) {
                System.out.println("Invalid Input");
                sc.next();
            }
        } while (check <= 1 && check >= 5);
        // Add Income
        if (check == 1) {
            double Income;
            String catalog = "";
            double IncomeTotal = 0;
            catalog = JOptionPane.showInputDialog("What is your income : ");
            Income = Integer.parseInt(JOptionPane.showInputDialog("How much is it   "));

            person.addIncome(person.getPerId(), day, catalog, Income);
            person.update();
        } //Add Expense
        else if (check == 2) {
            double Expense;
            String catalog = "";
            catalog = JOptionPane.showInputDialog("What is your expense :");
            Expense = Integer.parseInt(JOptionPane.showInputDialog("How much is it   "));
            person.addExpense(person.getPerId(), day, catalog, Expense);
            person.update();
        } //Add Save 
        else if (check == 3) {
            double Saving;
            double SavingTotal = 0;
            String catalog = "";

            Saving = Integer.parseInt(JOptionPane.showInputDialog("How much is it "));
            SavingTotal += Saving;
            person.addSave(person.getPerId(), day, catalog, Saving);
            person.update();
        } //History
        else if (check == 4) {
            String x;
            do {
                System.out.println("-----------------------------------------");
                System.out.println("YOUR HISTORY");
                System.out.println("Date                Type           Amount");
                System.out.println("-----------------------------------------");
                List<History> history = person.getHistory();
                if (history != null) {
                    int count = 1;
                    for (History h : history) {
                        if (count++ <= 1) {
                            System.out.println(h.getHistoryDateTime() + "   " + h.getHistoryDescription()
                                    + "           " + h.getAmount());
                        } else {
                            System.out.println(h.getHistoryDateTime() + "   " + h.getHistoryDescription()
                                    + "           " + h.getAmount());
                        }
                    }
                }
                System.out.println("-----------------------------------------");
                System.out.print("Back to menu (0 or back) : ");
                x = sc.next();
            } while (!x.equalsIgnoreCase("back") && !x.equalsIgnoreCase("0"));
        } //Searh
        else if (check == 5) {
            try {
                Connection conn = ConnectionDB.getConnection();
                long a = person.getPerId();
                String NAME = "Salary";
                PreparedStatement ps = conn.prepareStatement(
                        "SELECT * FROM  INCOME WHERE PERID = " + a + "  and CATALOG LIKE '%" + NAME + "%' ");
                ResultSet rec = ps.executeQuery();

                while ((rec != null) && (rec.next())) {
                    System.out.print(rec.getDate("Days"));
                    System.out.print(" - ");
                    System.out.print(rec.getString("CATALOG"));
                    System.out.print(" - ");
                    System.out.print(rec.getDouble("AMOUNT"));
                    System.out.print(" - ");
                }
                ps.close();
                conn.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } //Analy 
        else if (check == 6) {
            String x;
            do {
                DecimalFormat df = new DecimalFormat("##.##");
                double in = person.getIncome();
                double ex = person.getExpense();
                double sum = person.getSumin_ex();
                System.out.println("-----------------------------------------");
                System.out.println("Income : " + df.format((in / sum) * 100) + "%");
                System.out.println("Expense : " + df.format((ex / sum) * 100) + "%");
                System.out.println("\n\n");
                System.out.print("Back to menu (0 or back) : ");
                x = sc.next();
            } while (!x.equalsIgnoreCase("back") && !x.equalsIgnoreCase("0"));
        } //TOTAL
        else if (check == 7) {
            String x;
            do {
                System.out.println("-----------------------------------------");
                System.out.println("TOTALSAVE             TOTAL");
                System.out.println(
                        person.getTotalSave() + " Baht" + "             " + person.getTotal() + " Baht");
                System.out.println("\n\n");
                System.out.print("Back to menu (0 or back) : ");
                x = sc.next();
            } while (!x.equalsIgnoreCase("back") && !x.equalsIgnoreCase("0"));
        } //ALL Summy
        else if (check == 8) {
            String x;
            do {
                DecimalFormat df = new DecimalFormat("##.##");
                double in = person.getIncome();
                double ex = person.getExpense();
                double sum = person.getSumin_ex();
                double a = ((in / sum) * 100);
                double b = ((ex / sum) * 100);
                System.out.println("-----------------------------------------");
                System.out.println("ALL SUMMARY");
                System.out.println("Account: " + person.getPerName());
                System.out.println("");
                System.out.println("Total Save ------------- Total");
                System.out
                        .println(person.getTotalSave() + " Baht               " + person.getTotal() + " Baht");
                System.out.println("");

                System.out.println("INCOME --------------- EXPENSE");
                System.out.println(df.format(a) + "%" + "                  " + df.format(b) + "%");

                System.out.println("-----------------------------------------");
                System.out.println("\n\n");
                System.out.print("Back to menu (0 or back) : ");
                x = sc.next();
            } while (!x.equalsIgnoreCase("back") && !x.equalsIgnoreCase("0"));
        } //LOG OUT 
        else {
            System.out.println("See ya.\n");
            login = false;
            break;
        }
    } while (true);
}

From source file:simcommunity.TheSim.java

public static void main(String[] args) {

    Scanner valore = new Scanner(System.in);

    System.out.print("\n===================================");
    System.out.print("\nSIMULAZIONE COMUNITA'");
    System.out.print("\nPARISI-NICOLUSSI-SITA'");
    System.out.print("\nemail: r.nicolussi@gmail.com ");
    System.out.print("\n===================================");

    System.out.print("\n\nChe tipo di simulazione vuoi eseguire? \n1) interattiva\n"
            + "2) batch con individui fissi, connessioni variabili\n"
            + "3) batch con connessioni fisse,  individui variabili\n" + "4) batch completo\n"
            + "5) batch completo con collegamenti espressi in % ");
    int scelta = valore.nextInt();

    switch (scelta) {

    case 1:/*  www  .  j a va  2s.  c  om*/
        interactiveSim();
        break;
    case 2:
        batchSim_fixedindividui();
        break;
    case 3:
        batchSim_fixedconnessioni();
        break;
    case 4:
        batchSim_completa();
        break;
    case 5:
        batchSim_completa_percentuali();
        break;
    }

}

From source file:com.precioustech.fxtrading.oanda.restapi.marketdata.historic.HistoricMarketDataOnDemandDemo.java

public static void main(String[] args) throws Exception {
    usage(args);//  ww  w . ja v a 2  s .  c  o m
    final String url = args[0];
    final String accessToken = args[1];
    HistoricMarketDataProvider<String> historicMarketDataProvider = new OandaHistoricMarketDataProvider(url,
            accessToken);
    Scanner scanner = new Scanner(System.in);
    scanner.useDelimiter(System.getProperty("line.separator"));
    System.out.print("Instrument" + TradingConstants.COLON);
    String ccyPair = scanner.next();
    TradeableInstrument<String> instrument = new TradeableInstrument<>(ccyPair.toUpperCase());

    System.out.print(
            "Granularity" + ArrayUtils.toString(CandleStickGranularity.values()) + TradingConstants.COLON);
    CandleStickGranularity granularity = CandleStickGranularity.valueOf(scanner.next().toUpperCase());
    System.out.print("Time Range Candles(t) or Last N Candles(n)?:");
    String choice = scanner.next();

    List<CandleStick<String>> candles = null;
    if ("t".equalsIgnoreCase(choice)) {
        System.out.print("Start Time(" + datefmtLabel + ")" + TradingConstants.COLON);
        String startStr = scanner.next();
        Date startDt = sdf.parse(startStr);
        System.out.print("  End Time(" + datefmtLabel + ")" + TradingConstants.COLON);
        String endStr = scanner.next();
        Date endDt = sdf.parse(endStr);
        candles = historicMarketDataProvider.getCandleSticks(instrument, granularity,
                new DateTime(startDt.getTime()), new DateTime(endDt.getTime()));
    } else {
        System.out.print("Last how many candles?" + TradingConstants.COLON);
        int n = scanner.nextInt();
        candles = historicMarketDataProvider.getCandleSticks(instrument, granularity, n);
    }
    System.out.println(center("Time", timeColLen) + center("Open", priceColLen) + center("Close", priceColLen)
            + center("High", priceColLen) + center("Low", priceColLen));
    System.out.println(repeat("=", timeColLen + priceColLen * 4));
    for (CandleStick<String> candle : candles) {
        System.out.println(center(sdf.format(candle.getEventDate().toDate()), timeColLen)
                + formatPrice(candle.getOpenPrice()) + formatPrice(candle.getClosePrice())
                + formatPrice(candle.getHighPrice()) + formatPrice(candle.getLowPrice()));
    }
    scanner.close();
}

From source file:bankconsoleapp.console.Main.java

/**
 * @param args the command line arguments
 *//*  ww w  .jav  a  2s  . co  m*/
public static void main(String[] args) {

    //Injecting applicationContext to main
    ApplicationContext context = new ClassPathXmlApplicationContext("bankconsoleapp/applicationContext.xml");

    EmployeeService eS = context.getBean("EmployeeService", EmployeeService.class);
    CustomerService cS = context.getBean("CustomerService", CustomerService.class);
    SavingService sS = context.getBean("SavingService", SavingService.class);

    String userName, pass;
    Scanner in = new Scanner(System.in);
    boolean user = false;
    boolean savingRedo = false;

    do {

        System.out.println("Enter Employee ID:");
        userName = in.nextLine();
        for (Employee emp : eS.getAllEmp()) {
            if (userName.equals(emp.geteID())) {
                System.out.println("Password:");
                pass = in.nextLine();
                for (Employee em : eS.getAllEmp()) {
                    if (pass.equals(em.getPassword())) {

                        user = true;
                    }
                }
            }
        }

    } while (!user);

    long start = System.currentTimeMillis();
    long end = start + 60 * 1000; // 60 seconds * 1000 ms/sec
    int operation = 0;
    int userChoice;

    boolean quit = false;
    do {
        System.out.println("ACME Bank Saving System:");
        System.out.println("------------------------");
        System.out.println("1. Create Customer & Saving Account");
        System.out.println("2. Deposit Money");
        System.out.println("3. Withdraw Money");
        System.out.println("4. View Balance");
        System.out.println("5. Quit");
        System.out.print("Operation count: " + operation + "(Shut down at 5)");
        userChoice = in.nextInt();
        switch (userChoice) {
        case 1:

            //create customer, then saving account regard to existing customer( maximum 2 SA per Customer)
            System.out.println("Create Customer :");
            String FirstN, LastN, DoB, accNum, answer;

            Scanner sc = new Scanner(System.in);
            Customer c = new Customer();
            int saID = 0;

            System.out.println("Enter First Name:");
            FirstN = sc.nextLine();
            c.setFname(FirstN);
            System.out.println("Enter Last Name:");
            LastN = sc.nextLine();
            c.setLname(LastN);
            System.out.println("Enter Date of Birth:");
            DoB = sc.nextLine();
            c.setDoB(DoB);

            do {

                System.out.println("Creating saving acount, Enter Account Number:");
                accNum = sc.nextLine();
                c.setSA(accNum);
                c.setSavingAccounts(c.getSA());
                saID++;
                System.out.println("Create another SA? Y/N?");
                answer = sc.nextLine();
                if (answer.equals("n")) {
                    savingRedo = true;
                }
                if (saID == 2) {
                    System.out.println("Maximum Saving account reached!");
                }
            } while (!savingRedo && saID != 2);

            cS.createCustomer(c);
            operation++;

            break;
        case 2:
            // deposit

            String acNum;
            int amt;
            Scanner sc1 = new Scanner(System.in);
            System.out.println("Enter Saving Account number u wish to do deposit.");
            acNum = sc1.nextLine();
            System.out.println("Enter amount :");
            amt = sc1.nextInt();

            sS.deposit(acNum, amt);
            operation++;

            break;
        case 3:
            String acNums;
            int amts;
            Scanner sc2 = new Scanner(System.in);
            System.out.println("Enter Saving Account number u wish to do withdraw.");
            acNums = sc2.nextLine();
            System.out.println("Enter amount :");
            amts = sc2.nextInt();

            sS.withdraw(acNums, amts);
            operation++;
            break;

        case 4:
            // view
            System.out.println("Saving Account Balance:");
            System.out.println(sS.getAllSA());
            operation++;
            break;

        case 5:
            quit = true;
            break;
        default:
            System.out.println("Wrong choice.");
            break;
        }
        System.out.println();
        if (operation == 5) {
            System.out.println("5 operation reached, System shutdown.");
        }
        if (System.currentTimeMillis() > end) {
            System.out.println("Session Expired.");
        }
    } while (!quit && operation != 5 && System.currentTimeMillis() < end);
    System.out.println("Bye!");

}

From source file:Main.java

public static int[] readNumsFromCommandLine() {
    Scanner s = new Scanner(System.in);
    int count = s.nextInt();
    s.nextLine(); // throw away the newline.
    int[] numbers = new int[count];
    Scanner numScanner = new Scanner(s.nextLine());
    for (int i = 0; i < count; i++) {
        if (numScanner.hasNextInt()) {
            numbers[i] = numScanner.nextInt();
        } else {/*from w  w w . j  a v a 2 s  .  c  o  m*/
            System.out.println("You didn't provide enough numbers");
            break;
        }
    }
    return numbers;
}

From source file:Main.java

static void parseLine(String line) {
    Scanner lineScanner = new Scanner(line);
    lineScanner.useDelimiter("\\s*,\\s*");
    String name = lineScanner.next();
    int age = lineScanner.nextInt();
    boolean isCertified = lineScanner.nextBoolean();
    System.out.println("It is " + isCertified + " that " + name + ", age " + age + ", is certified.");
}