Advertisement
CR7CR7

ScannerAndParse

Sep 12th, 2022
843
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.14 KB | None | 0 0
  1. package com.telerikacademy;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class ScannerAndParseNumbers {
  6.     public static void main(String[] args) {
  7.         Scanner scanner = new Scanner(System.in);
  8.  
  9.         // Takes the whole line from the console as text (for example "123")
  10.         String numberAsText = scanner.nextLine();
  11.  
  12.         // Transforms or parses the text "123" into the number 123
  13.         int number = Integer.parseInt(numberAsText);
  14.  
  15.         number = number - 1; //123 - 1 = 122
  16.  
  17.         // This won't compile as we cannot subtract 1 from a text
  18.         // Operator '-' cannot be applied to 'java.lang.String', 'int'
  19.         // numberAsText = numberAsText -1;
  20.  
  21.         // "+" operator means concatenate between strings
  22.         // This will produce: "123" + "1" = "1231"
  23.         numberAsText = numberAsText + 1;
  24.  
  25.         // Print the string
  26.         // Use %s to format it
  27.         System.out.printf("numberAsText value: %s", numberAsText);
  28.  
  29.         //Use to print new line
  30.         System.out.println();
  31.  
  32.         // Print the string
  33.         // Use %d to format it
  34.         System.out.printf("number value: %d", number);
  35.     }
  36. }
  37.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement