Example usage for java.util Scanner Scanner

List of usage examples for java.util Scanner Scanner

Introduction

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

Prototype

public Scanner(ReadableByteChannel source) 

Source Link

Document

Constructs a new Scanner that produces values scanned from the specified channel.

Usage

From source file:$.StartServer.java

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

        initSpringContainer();/*from ww  w  .  j  av a2 s .  c o m*/

        context.start();

        System.out.println("you can close spring container by input shutdown command");

        while (true) {
            scanner = new Scanner(System.in);
            if ("shutdown".equalsIgnoreCase(scanner.next())) {
                scanner.close();
                break;
            }
        }

        closeSpringContainer();
    }

From source file:StackTraceTest.java

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.print("Enter n: ");
    int n = in.nextInt();
    factorial(n);//from   www. ja  va2s  .c  o  m
}

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;//from   ww  w .  j a va 2  s.c o  m
    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:EchoServer.java

public static void main(String[] args) {
    try {//from   ww w  .  ja  v a2  s  . co  m
        // establish server socket
        ServerSocket s = new ServerSocket(8189);

        // wait for client connection
        Socket incoming = s.accept();
        try {
            InputStream inStream = incoming.getInputStream();
            OutputStream outStream = incoming.getOutputStream();

            Scanner in = new Scanner(inStream);
            PrintWriter out = new PrintWriter(outStream, true /* autoFlush */);

            out.println("Hello! Enter BYE to exit.");

            // echo client input
            boolean done = false;
            while (!done && in.hasNextLine()) {
                String line = in.nextLine();
                out.println("Echo: " + line);
                if (line.trim().equals("BYE"))
                    done = true;
            }
        } finally {
            incoming.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.bluexml.tools.miscellaneous.Translate.java

/**
 * @param args/*w ww  . ja  va 2  s. c o m*/
 */
public static void main(String[] args) {
    System.out.println("Translate.main() 1");
    Console console = System.console();

    System.out.println("give path to folder that contains properties files");
    Scanner scanIn = new Scanner(System.in);

    try {
        // TODO Auto-generated method stub
        String sWhatever;

        System.out.println("Translate.main() 2");
        sWhatever = scanIn.nextLine();
        System.out.println("Translate.main() 3");

        System.out.println(sWhatever);

        File inDir = new File(sWhatever);

        FilenameFilter filter = new FilenameFilter() {

            public boolean accept(File arg0, String arg1) {
                return arg1.endsWith("properties");
            }
        };
        File[] listFiles = inDir.listFiles(filter);
        for (File file : listFiles) {

            prapareFileToTranslate(file, inDir);

        }

        System.out.println("please translate text files and press enter");
        String readLine = scanIn.nextLine();
        System.out.println("Translate.main() 4");
        for (File file : listFiles) {

            File values = new File(file.getParentFile(), file.getName() + ".txt");
            writeBackValues(values, file);
            values.delete();
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        scanIn.close();
    }

}

From source file:GGbot.pkg0.Mainclass.java

public static void main(String[] args)
        throws InterruptedException, TwitterException, DbxException, IOException, Exception {

    String input = "";

    System.out.println("Welcomet to GGbot\nFor more information please take a look at the Read Me\n");

    System.out.println("- Twitter: PlayerName   (flex, returns the latest tweets from a player)\n"
            + "- Facebook: PlayerName  (flex, returns all the information available about a player)\n"
            + "- Note to self: Input   (notflex, create a new text document with your input, and put it in a drop box)\n"
            + "- Translate: Input      (notflex, detects the language of your input and translate it to english)\n"
            + "- Wiki                  (flex, returns the definition of league of legends from wikipedia\n"
            + "- !Players:             (returns the list of the players available in the library (only players from the teams: Cloud9, CLG, and TSM are available at the moment))\n"
            + "- !dropbox:             (returns the link to the dropbox)\n\n" + "Start to chat now!\n");
    while (!input.contains("bye")) {
        System.out.print("<User>");
        Scanner scanner = new Scanner(System.in);
        input = scanner.nextLine();//from  w  ww . j a  va  2s  .c om

        String output = bot.Bot(input.toLowerCase().trim());
        System.out.println("<GGbot>" + WordUtils.wrap(output, 75));
    }

}

From source file:com.git.ifly6.components.Census.java

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);

    try {// www .ja va  2  s .  c o  m
        region = new NSRegion(args[0]);
    } catch (ArrayIndexOutOfBoundsException e) {
        System.out.print("Please input the name of your region: \t");
        region = new NSRegion(scan.nextLine());
    }

    try {

        HashMap<String, Integer> endoMap = new HashMap<String, Integer>();
        String[] waMembers = region.getWAMembers();
        int[] valueCount = new int[waMembers.length];

        System.out.println(
                "[INFO] This census will take: " + time((int) Math.round(waitTime * waMembers.length)));

        for (int i = 0; i < waMembers.length; i++) {
            NSNation nation = new NSNation(waMembers[i]);
            valueCount[i] = nation.getEndoCount();
            endoMap.put(waMembers[i], new Integer(valueCount[i]));

            System.out.println("[LOG] Fetched information for: " + waMembers[i] + ", " + (i + 1) + " of "
                    + waMembers.length);
        }

        TreeMap<String, Integer> sortedMap = sortByValue(endoMap);

        int current = 0;
        int previous = sortedMap.firstEntry().getValue();

        System.out.printf("%-35s %12s %12s%n", "Nations", "Endorsements", "Difference");
        System.out.println("-------------------------------------------------------------");

        for (Map.Entry<String, Integer> entry : sortedMap.entrySet()) {

            String nationName = StringUtils.capitalize(entry.getKey().replace('_', ' '));
            current = entry.getValue();

            if ((previous - current) != 0) {
                System.out.printf("%-35s %12s %12s%n", nationName, entry.getValue(), (previous - current));
            } else {
                System.out.printf("%-35s %12s %12s%n", nationName, entry.getValue(), "-");
            }

            previous = entry.getValue();
        }

        System.out.println("-------------------------------------------------------------");
        System.out.printf("%-35s %12s %12s%n", "Delegate", "Endorsements", "Proportion");
        System.out.printf("%-35s %12s %12s%n",
                StringUtils.capitalize(sortedMap.firstEntry().getKey().replace('_', ' ')),
                sortedMap.firstEntry().getValue(),
                (double) (sortedMap.firstEntry().getValue() / waMembers.length));

    } catch (IOException e) {
        printError("Failed to fetch WA members or get endorsements in this region. "
                + "Check your internet connection or the state of the API.");
    }

    scan.close();
}

From source file:ExecSQL.java

public static void main(String args[]) {
        try {/*from www. ja va  2  s . c  o  m*/
            Scanner in;
            if (args.length == 0)
                in = new Scanner(System.in);
            else
                in = new Scanner(new File(args[0]));

            Connection conn = getConnection();
            try {
                Statement stat = conn.createStatement();

                while (true) {
                    if (args.length == 0)
                        System.out.println("Enter command or EXIT to exit:");

                    if (!in.hasNextLine())
                        return;

                    String line = in.nextLine();
                    if (line.equalsIgnoreCase("EXIT"))
                        return;
                    if (line.trim().endsWith(";")) // remove trailing semicolon
                    {
                        line = line.trim();
                        line = line.substring(0, line.length() - 1);
                    }
                    try {
                        boolean hasResultSet = stat.execute(line);
                        if (hasResultSet)
                            showResultSet(stat);
                    } catch (SQLException ex) {
                        for (Throwable e : ex)
                            e.printStackTrace();
                    }
                }
            } finally {
                conn.close();
            }
        } catch (SQLException e) {
            for (Throwable t : e)
                t.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

From source file:TextFileTest.java

public static void main(String[] args) {
    Employee[] staff = new Employee[3];

    staff[0] = new Employee("Carl Cracker", 75000, 1987, 12, 15);
    staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
    staff[2] = new Employee("Tony Tester", 40000, 1990, 3, 15);

    try {/*from ww  w  .  j  a va 2 s.  c om*/
        // save all employee records to the file employee.dat
        PrintWriter out = new PrintWriter("employee.dat");
        writeData(staff, out);
        out.close();

        // retrieve all records into a new array
        Scanner in = new Scanner(new FileReader("employee.dat"));
        Employee[] newStaff = readData(in);
        in.close();

        // print the newly read employee records
        for (Employee e : newStaff)
            System.out.println(e);
    } catch (IOException exception) {
        exception.printStackTrace();
    }
}

From source file:net.airvantage.sample.AirVantageExampleFlow2.java

public static void main(String[] args) {

    String apiUrl = "https://na.airvantage.net/api";
    // Replace these with your own api key and secret
    String apiKey = "your_app_id";
    String apiSecret = "your_api_secret";

    String login = null;//from  ww  w  .  j  a va  2  s . c o  m
    String password = null;
    String access_token = null;

    Scanner in = new Scanner(System.in);

    System.out.println("=== AirVantage's OAuth Workflow ===");
    System.out.println();

    // Obtain User/Password
    System.out.println("Enter your login:");
    System.out.print(">>");
    login = in.nextLine();
    System.out.println();
    System.out.println("...and your password:");
    System.out.print(">>");
    password = in.nextLine();
    System.out.println();

    // Get the Access Token
    System.out.println("Getting the Access Token...");
    System.out.println(apiUrl + "/oauth/token?grant_type=password&username=" + login + "&password=" + password
            + "&client_id=" + apiKey + "&client_secret=" + apiSecret);
    try {
        access_token = Request
                .Get(apiUrl + "/oauth/token?grant_type=password&username=" + login + "&password=" + password
                        + "&client_id=" + apiKey + "&client_secret=" + apiSecret)
                .execute().handleResponse(new ResponseHandler<String>() {

                    public String handleResponse(final HttpResponse response) throws IOException {
                        StatusLine statusLine = response.getStatusLine();
                        HttpEntity entity = response.getEntity();
                        if (statusLine.getStatusCode() >= 300) {
                            throw new HttpResponseException(statusLine.getStatusCode(),
                                    statusLine.getReasonPhrase());
                        }
                        if (entity == null) {
                            throw new ClientProtocolException("Response contains no content");
                        }

                        try {
                            String content = IOUtils.toString(entity.getContent());
                            JSONObject result = new JSONObject(content);
                            return result.getString("access_token");
                        } catch (JSONException e) {
                            throw new ClientProtocolException("Malformed JSON", e);
                        }
                    }

                });

        System.out.println("Got the Access Token!");
        System.out.println("(if you're curious it looks like this: " + access_token + " )");
        System.out.println();

        // Now let's go and ask for a protected resource!
        System.out.println("Now we're going to get info about the current user...");

        JSONObject result = Request.Get(apiUrl + "/v1/users/current?access_token=" + access_token).execute()
                .handleResponse(new ResponseHandler<JSONObject>() {

                    public JSONObject handleResponse(final HttpResponse response) throws IOException {
                        StatusLine statusLine = response.getStatusLine();
                        HttpEntity entity = response.getEntity();
                        if (statusLine.getStatusCode() >= 300) {
                            throw new HttpResponseException(statusLine.getStatusCode(),
                                    statusLine.getReasonPhrase());
                        }
                        if (entity == null) {
                            throw new ClientProtocolException("Response contains no content");
                        }

                        try {
                            String content = IOUtils.toString(entity.getContent());
                            return new JSONObject(content);
                        } catch (JSONException e) {
                            throw new ClientProtocolException("Malformed JSON", e);
                        }
                    }

                });

        System.out.println("Got it! Let's see what we found...");
        System.out.println();
        System.out.println(result.toString());

        System.out.println();
        System.out.println("That's it man! Go and build something awesome with AirVantage! :)");
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}