예제 #1
1
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    System.out.print("Please enter your name :");
    String userName = sc.nextLine();

    System.out.print("Wow, " + userName);
    System.out.print(", your name is " + userName.length());
    System.out.println(" characters long (if I count the spaces).");

    // now count how many alphabetic characters there are in the name
    String lowerCaseName = userName.toLowerCase();
    // counter for the number of letters
    int count = 0;
    for (int i = 0; i < lowerCaseName.length(); i++) {
      // if the character is alphabetic, then increment count
      char letter = lowerCaseName.charAt(i);
      if ((letter >= 'a' && letter <= 'z')) count++;
    }
    System.out.println("There are " + count + " letters in your name");

    for (int i = lowerCaseName.length() - 1; i >= 0; i--) {
      System.out.print(lowerCaseName.charAt(i));
    }
    System.out.println("");

    // find the position of the space
    String firstName;
    int spacePos = userName.indexOf(' ');
    if (spacePos == -1) firstName = userName;
    else firstName = userName.substring(0, spacePos);
    System.out.println("First name :" + firstName);
  }
예제 #2
1
파일: RSA.java 프로젝트: raykroc/crypto
  public static void main(String[] args) {
    long st, dt, et;
    String plaintext1 = "Yellow and Black Border Collies";
    String keysPath = "keys.txt";
    RSA rsa;

    try {
      Scanner in = new Scanner(new FileReader(keysPath));
      BigInteger n = new BigInteger(in.nextLine().substring(3));
      BigInteger e = new BigInteger(in.nextLine().substring(3));
      BigInteger d = new BigInteger(in.nextLine().substring(3));
      in.close();

      rsa = new RSA(n, e, d);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      return;
    }

    //		rsa = new RSA(8, 1024);

    st = System.currentTimeMillis();
    String ciphertext = rsa.encrypt(plaintext1);
    dt = System.currentTimeMillis();
    String plaintext2 = rsa.decrypt(ciphertext);
    et = System.currentTimeMillis();

    System.out.println("enc time: " + (dt - st));
    System.out.println("dec time: " + (et - dt));
    System.out.println(plaintext2);

    // rsa.saveKeys(keysPath);
  }
  public static void main(String[] args) {

    float numero1, numero2;
    float suma;
    float producto;
    float media;

    Scanner teclado = new Scanner(System.in);

    System.out.print("Dame un número: ");
    numero1 = teclado.nextFloat();
    System.out.print("Dame otro número: ");
    numero2 = teclado.nextFloat();

    suma = numero1 + numero2;
    producto = numero1 * numero2;
    media = (numero1 + numero2) / 2;

    System.out.println("--------RESULTADOS--------");
    System.out.println("Número 1: " + numero1);
    System.out.println("Número 2: " + numero2);
    System.out.println("Suma: " + suma);
    System.out.println("Producto: " + producto);
    System.out.println("Media: " + media);

    teclado.close();
  }
예제 #4
0
  @SuppressWarnings("resource")
  public static void main(String[] args) {

    Scanner reader = new Scanner(System.in);
    if (anagram(reader.nextLine())) System.out.println("YES");
    else System.out.println("NO");
  }
예제 #5
0
  public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    String input = scan.nextLine();
    String[] intStrings = input.split(" ");
    // Konverter til integer:
    int[] measurements = new int[intStrings.length];
    int sum = 0;
    // En slags loop
    for (int i = 0; i < intStrings.length; i++) {
      int j = Integer.parseInt(intStrings[i]);
      measurements[i] = j;
      sum += j;
    }
    double mean = ((double) sum) / measurements.length;

    double varSum = 0;
    // Iteration
    for (int i : measurements) {
      varSum += Math.pow(i - mean, 2);
    }

    System.out.println("Mean: " + mean);
    System.out.println("Standard deviation: " + Math.sqrt(varSum / measurements.length));
    scan.close();
  }
 public void init() {
   Scanner scan = new Scanner(System.in);
   count = scan.nextInt();
   x0 = scan.nextLong();
   y0 = scan.nextLong();
   int result = 0;
   boolean special = false;
   for (int i = 0; i < count; i++) {
     long tempx = scan.nextLong();
     long tempy = scan.nextLong();
     if (tempx == x0 && tempy == y0) {
       special = true;
       continue;
     }
     boolean isDuplicate = false;
     for (int j = 0; j < result; j++) {
       long x1 = xList.get(j);
       long y1 = yList.get(j);
       if ((x1 - x0) * (tempy - y0) == (y1 - y0) * (tempx - x0)) {
         isDuplicate = true;
         break;
       }
     }
     if (!isDuplicate) {
       xList.add(tempx);
       yList.add(tempy);
       result++;
     }
   }
   if (special && result == 0) result = 1;
   System.out.println(result);
   scan.close();
 }
예제 #7
0
  public static void main(String[] args) {
    int n;
    Scanner input = new Scanner(System.in);
    // read a number from the console
    do {
      System.out.print("Enter the size of an array: ");
      n = input.nextInt();
    } while (n < 3);

    // declare the array
    int[] array = new int[n];

    // fill the array
    for (int i = 0; i < array.length; i++) {
      System.out.print("Enter a number: ");
      array[i] = input.nextInt();
    }

    input.close();

    // check if the array is zigzag
    boolean isJagged = true;
    for (int i = 1; i < array.length - 1; i += 2) {
      if (!((array[i - 1] < array[i]) && (array[i] > array[i + 1]))) {
        isJagged = false;
        break;
      }
    }
    if (isJagged) {
      System.out.println("изпълнява изискванията за зигзагообразна нагоре редица");
    } else {
      System.out.println("не изпълнява изискванията за зигзагообразна нагоре редица");
    }
  }
  private static boolean isInteger(String s, int radix) {
    Scanner sc = new Scanner(s.trim());
    if (!sc.hasNextInt(radix)) return false;

    sc.nextInt(radix);
    return !sc.hasNext();
  }
예제 #9
0
  public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    String input = scan.next();

    //		System.out.println(checkUnique(input));
    System.out.println(checkUniqueInLinear(input));
  }
예제 #10
0
  public static Map<String, ArrayList<String>> prepareMap() {
    Map<String, ArrayList<String>> symbolMap = new HashMap<String, ArrayList<String>>();

    try {
      File file = new File("result.txt");
      Scanner scanner = new Scanner(file);
      while (scanner.hasNextLine()) {

        String currentLine = scanner.nextLine(); // <AAPL,128.62>
        String temString = currentLine.substring(1, currentLine.length() - 1);
        String[] strArray = temString.split(",");
        String key = strArray[0];
        String value = strArray[1];

        ArrayList<String> priceList = new ArrayList<>();
        if (symbolMap.containsKey(key)) {
          priceList = symbolMap.remove(key);
        }
        priceList.add(value);
        symbolMap.put(key, priceList);
      }
      scanner.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }

    return symbolMap;
  }
예제 #11
0
  public static void main(String[] args) throws UnknownHostException, IOException {
    Socket sock = new Socket("localhost", 1111);
    Scanner s = new Scanner(System.in);

    OutputStream out = sock.getOutputStream();
    InputStream in = sock.getInputStream();

    out.flush();
    byte[] buffer = new byte[1024];
    int n;
    String index = "";

    if ((n = in.read(buffer)) != -1) {
      System.out.println(new String(buffer, 0, n));
      String name = s.nextLine();
      out.write(name.getBytes());
    }
    while (true) {
      if ((n = in.read(buffer)) != -1) {

        if ((new String(buffer, 0, n)).equals("DONE")) {
          System.out.println("File uploaded successfully");
        } else {
          System.out.println(new String(buffer, 0, n));
          index = s.nextLine();
          out.write(index.getBytes());
          System.out.println(new String(buffer, 0, in.read(buffer)));
        }
      }
    }
  }
  public static LinkedList<String> readFromFile() {
    File f;
    Scanner scanner;
    LinkedList<String> result = new LinkedList<>();

    try {
      f = new File(fileName);
      scanner = new Scanner(f);
      // Pattern regex = Pattern.compile("\\w");

      while (scanner.hasNext()) {
        String current = scanner.next();
        String[] splitLine = current.split(",");

        for (int i = 0; i < splitLine.length; i++) {
          // Debug statement
          System.out.println("Scanner adding to list:" + splitLine[i]);
          result.add(splitLine[i]);
        }

        System.out.println("Scanner reading:" + current);
        // result.add(current);
        // System.out.println("Output of file" + );
      }

      return result;
    } catch (IOException exc) {
      System.out.println("Error reading file line" + exc.getMessage());
    }
    return null;
  }
예제 #13
0
  public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);

    int start = scan.nextInt();
    int end = scan.nextInt();

    int count = 0;

    for (int i = start; i <= end; i++) {
      String decimalStr = String.valueOf(i);
      for (int j = 0; j < decimalStr.length(); j++) {
        if (decimalStr.charAt(j) == '3'
            || decimalStr.charAt(j) == '6'
            || decimalStr.charAt(j) == '9') {
          count++;
          break;
        } else {
          if ((Integer.parseInt(decimalStr) % 3) == 0) {
            count++;
            break;
          }
        }
      }
    }
    System.out.println(count);
  }
예제 #14
0
 public ArrayList<Brick> getBricks(String fileName) {
   try {
     Scanner in = new Scanner(new File(fileName));
     ArrayList<String> lines = new ArrayList<>();
     while (in.hasNextLine()) {
       lines.add(in.nextLine());
     }
     in.close();
     char[][] chars = new char[lines.size()][];
     for (int i = 0; i < lines.size(); i++) {
       chars[i] = lines.get(i).toCharArray();
     }
     ArrayList<Brick> ret = new ArrayList<>();
     int width = 70, height = 40;
     for (int r = 0; r < chars.length; r++) {
       for (int c = 0; c < chars[r].length; c++) {
         if (chars[r][c] != ' ') {
           int x = c * width;
           int y = r * height;
           ret.add(new Brick(x, y, width, height));
         }
       }
     }
     return ret;
   } catch (FileNotFoundException e) {
     e.printStackTrace();
     return null;
   }
 }
  /** @param args the command line arguments */
  public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    // Enter annual interest rate in percentage, e.g., 7.25%
    System.out.print("Enter annual interest rate (e.g., 7.25%): ");
    double annualInterestRate = sc.nextDouble();

    // Obtain monthly interest rate
    double monthlyInterestRate = computeMonthlyInterestRate(annualInterestRate);

    // Enter number of years
    System.out.print("Enter number of years as an integer (e.g., 5): ");
    int numberOfYears = sc.nextInt();

    // Enter loan amount
    System.out.print("Enter loan amount (e.g., 120000.95): ");
    double loanAmount = sc.nextDouble();

    // Calculate monthly payment
    double monthlyPayment = computeMonthlyPayment(loanAmount, monthlyInterestRate, numberOfYears);

    double totalPayment = monthlyPayment * numberOfYears * 12;

    // Display results
    System.out.printf("The monthly payment: $%8.2f%n", (int) (monthlyPayment * 100) / 100.0);
    System.out.printf("The total payment:   $%8.2f%n", (int) (totalPayment * 100) / 100.0);
  }
예제 #16
0
  public static void main(String[] args) {
    // Initialise Variables
    String FirstName;
    String LastName;
    String Result;

    Scanner input = new Scanner(System.in);

    // prompts the user to enter firstname
    System.out.print("Please Enter First Name: ");
    FirstName = input.next();

    // prompts the user to enter lastname
    System.out.print("Please Enter Last Name: ");
    LastName = input.next();

    // Display Name
    System.out.println("Name is:" + FirstName + " " + LastName);

    // To generate Random Numbers within 10 to 99
    int randomNum = 10 + (int) (Math.random() * 99);

    // To Add first letter of the user's first name (John), followed by the first five characters
    // of the user's last name(Smith), followed by a random number in the range 10 to 99.
    Result = FirstName.substring(0, 1) + LastName.substring(0, 5) + randomNum;

    // To display the output.
    System.out.println("Output is:" + Result);
  }
 public ArrayList<ArticleDTO> add() {
   @SuppressWarnings("resource")
   Scanner input = new Scanner(System.in);
   String author;
   String title;
   String content;
   ArrayList<ArticleDTO> articles = new ArrayList<ArticleDTO>();
   do {
     author = UtilView.getStringKeyboard("Please Enter Author : ");
     title = UtilView.getStringKeyboard("Please Enter Title : ");
     System.out.println("Type 3 periods (...) to stop");
     System.out.print("Please Enter Content: ");
     content = UtilView.inputContent();
     articles.add(new ArticleDTO(1, author, title, content, UtilView.currentDate()));
     // logfile.writeLogAdd(newArticle);
     System.out.print("Do you want to continues?(Y/N)");
     String confirm = input.next();
     switch (confirm.toLowerCase()) {
       case "y":
         break;
       default:
         return articles;
     } // End switch;
   } while (true);
 } // End of add();
예제 #18
0
  public static void main(String args[]) {
    Scanner input = new Scanner(System.in);
    int T = input.nextInt();
    CPoint[] array = new CPoint[SIZE];
    for (int t = 0; t < T; t++) {
      int n = input.nextInt();
      for (int i = 0; i < n; i++) {
        int a = input.nextInt();
        int b = input.nextInt();
        array[i] = new CPoint();
        array[i].setPoint(a, b);
      }

      int ans = 0;
      for (int i = 0; i < n; i++) {
        int sum = 0;
        for (int j = 0; j < n; j++)
          if (i != j) {
            if (array[j].x > array[i].x && array[j].y > array[i].y) sum++;
            if (array[j].x < array[i].x && array[j].y < array[i].y) sum++;
          }
        if (sum > ans) ans = sum;
      }
      System.out.println(ans);
    }
  }
  // Start listener thread
  @Override
  public void run() {

    Scanner sc = new Scanner(System.in);
    String command;
    String[] tokens;

    // Listen to stdin commands
    while (true) {
      command = sc.nextLine();
      System.out.println("[Shell Debug]: command: \"" + command + "\"");
      tokens = command.split(StreamingClient.DELIM);

      switch (tokens[0]) {
        case "help":
          System.out.println("Commands: ");
          System.out.println("\thelp - display this message");
          System.out.println(
              "\trequest <arg1> <arg2> ... (whitespace separated) - send a request to the server");
          System.out.println("\tclose - send a signal to close connection");
          System.out.println("\tclear - clear console");
          break;
        case "request": // Sends a request message
          break;
        case "close":
          StreamingClient.sendMessage("Close");
          StreamingClient.setConnected(false);
          return;
        case "clear":
          clear();
          break;
      }
    }
  }
예제 #20
0
  public static void main(String[] args) throws IOException {
    System.out.println("Программа \"Консольный калькулятор\"");
    System.out.println(
        "Поддерживаемые операции: сложение (+), вычитание (-), умножение (*) и деление (/)");

    Scanner scanner = new Scanner(System.in);

    System.out.print("Введите знак операции: ");
    String operation = scanner.nextLine();
    System.out.print("Введите первое число: ");
    double valueOne = scanner.nextDouble();
    System.out.print("Введите второе число: ");
    double valueTwo = scanner.nextDouble();

    if (operation.equals("+")) {
      System.out.println("Результат операции сложение: " + (valueOne + valueTwo));
    } else if (operation.equals("-")) {
      System.out.println("Результат операции вычитание: " + (valueOne - valueTwo));
    } else if (operation.equals("*")) {
      System.out.println("Результат операции умножение: " + (valueOne * valueTwo));
    } else if (operation.equals("/")) {
      System.out.println("Результат операции деление: " + (valueOne / valueTwo));
    } else {
      System.out.println("Извините, но операция \"" + operation + "\" не поддерживается.");
    }
  }
예제 #21
0
 public static void main(String[] args) {
   int sum = 0, A, B, tem;
   Scanner sc = new Scanner(System.in);
   System.out.println("Ingresa el valor de A ");
   A = sc.nextInt();
   System.out.println("Ingresa el valor de B ");
   B = sc.nextInt();
   String cad = "";
   for (int i = A; i <= B; i = i + 5) {
     cad = cad + " " + i;
     sum = sum + i;
   }
   System.out.println(cad);
   System.out.println("La suma de los multiplos es:" + sum);
   if (A == 0) {
     System.out.println("El numero " + A + " es nulo");
   }
   if (A > 0) {
     System.out.println("El numero " + A + " es positivo");
   } else {
     System.out.println("El numero " + A + " es negativo");
   }
   if (A < B) {
     tem = A;
     A = B;
     B = tem;
     System.out.println("Ahora el valor de A es: " + A + " y el valor de B es: " + B);
   }
 }
예제 #22
0
 public static String requestName() {
   Scanner keyboard = new Scanner(System.in);
   System.out.print("Name: ");
   String name = keyboard.nextLine();
   keyboard.close();
   return name;
 }
  public static Languages getInstance(String languagesResourceName) {
    // read languages list
    Set<String> ls = new HashSet<String>();
    InputStream langIS =
        Languages.class.getClassLoader().getResourceAsStream(languagesResourceName);

    if (langIS == null) {
      throw new IllegalArgumentException(
          "Unable to resolve required resource: " + languagesResourceName);
    }

    Scanner lsScanner = new Scanner(langIS, ResourceConstants.ENCODING);
    boolean inExtendedComment = false;
    while (lsScanner.hasNextLine()) {
      String line = lsScanner.nextLine().trim();
      if (inExtendedComment) {
        if (line.endsWith(ResourceConstants.EXT_CMT_END)) {
          inExtendedComment = false;
        } else {
          // skip
        }
      } else {
        if (line.startsWith(ResourceConstants.EXT_CMT_START)) {
          inExtendedComment = true;
        } else if (line.length() > 0) {
          ls.add(line);
        } else {
          // skip blank lines
        }
      }
    }

    return new Languages(Collections.unmodifiableSet(ls));
  }
예제 #24
0
  public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.print("Enter 10 ints: ");
    int A[] = new int[10];
    for (int j = 0; j < 10; j++) {
      A[j] = scan.nextInt();
    }

    int min = 10000;
    int max = -10000;
    for (int j = 0; j < 10; j++) {
      if (A[j] < min) {
        min = A[j];
      }
      if (A[j] > max) {
        max = A[j];
      }
    }
    System.out.println("The lowest entry is: " + min);
    System.out.println("The highest entry is: " + max);
    int sum = 0;
    for (int j = 0; j < 10; j++) {
      sum = sum + A[j];
    }
    System.out.println("The sum is: " + sum);
    for (int j = 0; j < 10; j++) {
      System.out.print(" " + A[j] + "  " + A[9 - j]);
      System.out.println("");
    }
  }
예제 #25
0
  public static void main(String[] args) {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
    Scanner sc = new Scanner(System.in);
    String[][] numArray = new String[6][];
    int largestSum = 0;
    for (int i = 0; i < 6; i++) {
      numArray[i] = sc.nextLine().split(" ");
    }

    for (int i = 0; i <= 3; i++) {
      for (int j = 0; j <= 3; j++) {
        int sum =
            Integer.parseInt(numArray[i][j])
                + Integer.parseInt(numArray[i][j + 1])
                + Integer.parseInt(numArray[i][j + 2])
                + Integer.parseInt(numArray[i + 1][j + 1])
                + Integer.parseInt(numArray[i + 2][j])
                + Integer.parseInt(numArray[i + 2][j + 1])
                + Integer.parseInt(numArray[i + 2][j + 2]);
        // System.out.println(sum);
        if (i == 0 && j == 0) {
          largestSum = sum;
        } else {
          if (sum > largestSum) {
            largestSum = sum;
          }
        }
      }
    }

    System.out.println(largestSum);
  }
예제 #26
0
  public static void main(String[] args) throws Exception {
    Scanner scan = new Scanner(System.in);
    int[] list = new int[20];
    for (int i = 0; i < list.length; i++) {
      String s = scan.nextLine();
      list[i] = Integer.parseInt(s);
    }
    scan.close();
    // TODO: implement here

    int[] list1Klein = new int[10];
    for (int k = 0; k < 10; k++) {

      list1Klein[k] = (list[k]);

      // TODO: implement point 4. Copy first 10

    }

    int[] list2Klein = new int[10];
    for (int k = 10; k < 20; k++) {

      list2Klein[k - 10] = (list[k]);
      System.out.println(list2Klein[k - 10]);
    }
  }
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    int count = sc.nextInt();
    int digitsNum;

    for (int i = 0; i < count; i++) {
      ArrayList<Integer> digits = new ArrayList<>();
      digitsNum = sc.nextInt();
      int result = 0;

      while (digitsNum > 0) {
        digits.add(digitsNum % 10);
        digitsNum = digitsNum / 10;
      }

      Collections.reverse(digits);

      for (int j = 0; j < digits.size(); j++) {
        int digit = digits.get(j);
        result += digit * (j + 1);
      }

      System.out.print(result + " ");
    }

    sc.close();
  }
예제 #28
0
파일: Client.java 프로젝트: VadimOza/Chat
  Client() {
    sc = new Scanner(new InputStreamReader(System.in));
    try {
      clientSocket = new Socket("localhost", 27015);
      System.out.println("Connected to server!");
      System.out.println("Enter your Nick: ");
      Scanner sc = new Scanner(new InputStreamReader(System.in));
      name = sc.nextLine();
    } catch (Exception ex) {
      System.out.println("Can't connect to server " + ex);
    }
    try {
      in = new DataInputStream(clientSocket.getInputStream());
      out = new DataOutputStream(clientSocket.getOutputStream());

      ClientReader reader = new ClientReader();
      reader.start();
      String str = "";
      while (!str.equals("exit")) {
        str = sc.nextLine();
        out.writeUTF(name + ": " + str);
      }
    } catch (Exception ex) {
      System.out.println("Err: " + ex);
    }
  }
예제 #29
0
  private int getMembers() {

    boolean valid = false; // indicates if the choice has been retrieved
    String members = null;
    Scanner keyboard = new Scanner(System.in); // keyboard input stream

    // prompt for the player's menu selection
    System.out.println(">>> Enter number of people in your household.");

    // get the choice from the keyboard and trim off the blanks

    members = keyboard.nextLine();
    members = members.trim();

    // if 'E' the control falls through and returns to Main Menu
    // then checks to validate input is integer
    // then checks for number selection between 1-25
    // if valid, perform doAction
    if (members.charAt(0) != 'E') {
      if (isInteger(members)) {
        // this is creating the new integer variable 'location'
        // and using a prepackaged function of parseInt from the
        // the available functions in the Integer class
        // to see the available functions, type 'Integer.' and hit enter.
        int m = Integer.parseInt(members);
        if (m > 0 && m < 51) {
          return m; // return the valid choice
        }
      } else {
        System.out.println("\n*** Invalid selection *** Try again.");
      }
    }
    return -1; // TODO else return user to locations menu;
  }
예제 #30
0
  public static void registerPatients(Socket socket) {
    Scanner scanner = new Scanner(System.in);
    long ICint = 0;
    String IC = null;
    int count = 0;

    try {
      System.out.println("Enter IC : ");
      ICint = scanner.nextLong();
    } catch (InputMismatchException e) {
      System.out.println("Please enter only integers.");
      return;
    }

    IC = String.valueOf(ICint);
    System.out.println("Searching for patient..");

    for (int i = 0; i < patientList.size(); i++) {
      if (patientList.get(i).IC.equals(IC)) {
        count++;
        System.out.println("Patient found! Added to queue.\n\n");
        patientQueue.add(patientList.get(i));
      }
    }

    if (count == 0) {
      System.out.println("Patient not found. Registering new entry.\n");
      registerNewPatient(IC, socket);
    }
  }