Пример #1
0
  public static void main(String[] args) throws FileNotFoundException {
    Scanner inFile = new Scanner(new FileReader("Lab3_input.txt"));
    PrintWriter outFile = new PrintWriter("Lab3_Exercise_output.txt");

    // Declare variables
    String lastName, firstName;
    double salary, pctRaise, salaryFinal;

    // set up while loop
    while (inFile.hasNext()) // condition checks to see if there is anything in the input file
    {
      // Read information from input file
      lastName = inFile.next();
      firstName = inFile.next();
      salary = inFile.nextDouble();
      pctRaise = inFile.nextDouble();

      // Calculate final salary
      salaryFinal = salary + (salary * pctRaise / 100);

      // Write file
      outFile.printf("%s %s %.2f%n", lastName, firstName, salaryFinal);
    }

    // Close input/output methods
    outFile.close();
    inFile.close();
  }
Пример #2
0
  public static void main(String[] args) {
    Scanner scanRadius = new Scanner(System.in);
    Scanner scanCenter = new Scanner(System.in);
    Point2D centerA = new Point2D.Double();
    Point2D centerB = new Point2D.Double();
    double x, y, radiusA = 0, radiusB = 0;

    for (char i = 'A'; i <= 'B'; i++) {
      System.out.print("\nCircle " + i);
      System.out.print("\nEnter center cordinates:" + "\n(x): ");
      x = scanCenter.nextDouble();
      System.out.print("(y): ");
      y = scanCenter.nextDouble();

      System.out.print("Enter radius: ");
      if (i == 'A') {
        radiusA = scanCenter.nextDouble();
        centerA.setLocation(x, y);
      } else if (i == 'B') {
        radiusB = scanCenter.nextDouble();
        centerB.setLocation(x, y);
      }
    }
    scanRadius.close();
    scanCenter.close();

    double distance = distance(centerA, centerB);

    if (distance == (radiusA + radiusB)) System.out.println("\nThe two circles are touching");
    else if ((distance < Math.abs(radiusA - radiusB)))
      System.out.println("\nOne circle encloses another");
    else if (distance < (radiusA + radiusB)) System.out.println("\nThe two circles overlap");
    else if (distance > (radiusA + radiusB)) System.out.println("\nThe two circles are separate");
  }
  /** @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);
  }
Пример #4
0
 public static void main(String[] args) {
   Scanner sc = new Scanner(System.in);
   while (true) {
     int n = sc.nextInt();
     if (n < 0) return;
     double pago = sc.nextDouble();
     double inicial = sc.nextDouble();
     int nval = sc.nextInt();
     for (int i = 0; i <= n; i++) {
       prc[i] = Double.POSITIVE_INFINITY;
     }
     for (int i = 0; i < nval; i++) {
       int pos = sc.nextInt();
       prc[pos] = sc.nextDouble();
     }
     double prcAnt = prc[0];
     double deuda = inicial;
     inicial += pago;
     pago = deuda / n;
     inicial = inicial - inicial * prcAnt;
     int i;
     for (i = 1; i <= n; i++) {
       if (deuda < inicial) {
         i = 0;
         break;
       }
       deuda -= pago;
       if (prc[i] != Double.POSITIVE_INFINITY) prcAnt = prc[i];
       inicial = inicial - inicial * prcAnt;
       if (deuda < inicial) break;
     }
     if (i == 1) System.out.println("1 month");
     else System.out.println(i + " months");
   }
 }
  public static void main(String[] args) {
    // Draw the UML diagram for the class and then implement the class.
    // Write a test
    // program that prompts the user to enter a, b, c, d, e, and f and
    // displays the result.
    // If ad - bc is 0, report that “The equation has no solution

    // skener za unos varijabli
    Scanner input = new Scanner(System.in);
    System.out.println("Unesite vrijednosti za a,b,c,d,e,f");
    double a = input.nextDouble();
    double b = input.nextDouble();
    double c = input.nextDouble();
    double d = input.nextDouble();
    double e = input.nextDouble();
    double f = input.nextDouble();
    // pravimo objekat nest sa konstruktorom kome prosljedjujemo varijable
    LinearEquation nest = new LinearEquation(a, b, c, d, e, f);
    // uslov
    if (nest.isSolvable() == false) {
      // ispis
      System.out.println("The equation has no solution!");
    } else {
      // ispis
      System.out.println("x = " + nest.getX() + " y = " + nest.getY());
    }
    // zatvaramo skener
    input.close();
  }
Пример #6
0
  public static void main(String[] args) {
    Scanner ulaz = new Scanner(System.in);
    // pravimo matrice
    double[][] matrix1 = new double[3][3];
    double[][] matrix2 = new double[3][3];

    try {
      // unos prve matrice
      System.out.println("Unesite elemente prve matrice:");
      for (int a = 0; a < matrix1.length; a++) {
        for (int b = 0; b < matrix1.length; b++) {
          matrix1[a][b] = ulaz.nextDouble();
        }
      }
      // unos druge matrice
      System.out.println("Unesite elemente druge matrice:");
      for (int a = 0; a < matrix2.length; a++) {
        for (int b = 0; b < matrix2.length; b++) {
          matrix2[a][b] = ulaz.nextDouble();
        }
      }
      System.out.println();

      množi(matrix1, matrix2);
    } catch (InputMismatchException ex) {
      System.out.println("GREŠKA: Neispravan unos podataka!");
      ulaz.close();
    }
  }
Пример #7
0
  public static void readParameters(String filename) throws IOException {
    BufferedReader in = new BufferedReader(new FileReader(filename));
    Scanner scanner = new Scanner(in);
    scanner.useDelimiter("[ \t\n,;()]+");

    su = scanner.nextInt();
    sv = scanner.nextInt();
    numImages = su * sv;
    System.out.println(su + " x " + sv);

    positions = new double[sv][su][2];
    for (int i = 0; i != numImages; ++i) {
      positions[i / su][i % su][0] = scanner.nextDouble();
      positions[i / su][i % su][1] = scanner.nextDouble();
    }

    int numCoefs = scanner.nextInt();
    coefs = new double[4][numCoefs];
    for (int i = 0; i != 4; ++i) {
      for (int j = 0; j != numCoefs; ++j) {
        coefs[i][j] = scanner.nextDouble();
        System.out.print(coefs[i][j] + ", ");
      }
      System.out.println();
    }
    System.out.println();

    // optional?
    perspectiveX = scanner.nextDouble();
    perspectiveY = scanner.nextDouble();
  }
 public static void main(String[] args) {
   // init object
   Account account1 = new Account(50.00);
   Account account2 = new Account(-7.53);
   // print objects balance
   System.out.printf("account1 balance: $%.2f\n", account1.getBalance());
   System.out.printf("account2 balance: $%.2f\n", account2.getBalance());
   // create scanner to read user input
   Scanner input = new Scanner(System.in);
   double depositAmount; // deposite amount read from user
   System.out.print("Enter deposit amount for account 1: ");
   depositAmount = input.nextDouble();
   System.out.printf("\nadding %.2f to account1 balance\n\n", depositAmount);
   account1.credit(depositAmount);
   // display message
   System.out.printf("account1 balance $%.2f\n", account1.getBalance());
   System.out.printf("account2 balance $%.2f\n", account2.getBalance());
   // prompt
   System.out.print("Enter deposit amount for account2: ");
   depositAmount = input.nextDouble();
   System.out.printf("\nadding %.2f to account2 balance\n\n", depositAmount);
   account2.credit(depositAmount);
   // display balance
   System.out.printf("account1 balance $%.2f\n", account1.getBalance());
   System.out.printf("account2 balance $%.2f\n", account2.getBalance());
 }
  /** This method will get the information to create an instance of a MarshmallowMonster. */
  private void MakeUserMonster() {
    // Step one: Get variables
    String userName;
    int userEyes;
    int userNoseCount;
    double userHair;
    double userLegs;
    boolean userBellyButton;

    // Step two: Define variables by using Scanner to get user input.
    System.out.println("Type in your name for your monster.");
    userName = monsterScanner.nextLine();
    System.out.println("Type in the number of eyes for your monster");
    userEyes = monsterScanner.nextInt();
    System.out.println("Type in the number of noses for you monster");
    userNoseCount = monsterScanner.nextInt();
    System.out.println("How much hair does your monster have? Type in a floating point or decimal");
    userHair = monsterScanner.nextDouble();
    System.out.println("How many legs?");
    userLegs = monsterScanner.nextDouble();
    System.out.println("Does it have a belly button? Type true or false");
    userBellyButton = monsterScanner.nextBoolean();

    // Step three: make a monster - use the constructor.
    userMonster =
        new MarshmallowMonsters(
            userName, userEyes, userNoseCount, userHair, userLegs, userBellyButton);
  }
  public static void main(String args[]) {
    // квадратное уравнение
    // a*x*x + b*x + c = 0
    // дискриминант D= b2-4ac

    Scanner s = new Scanner(System.in);

    System.out.print("Ввидите А : ");
    double a = s.nextDouble();

    System.out.print("Ввидите В : ");
    double b = s.nextDouble();

    System.out.print("Ввидите С : ");
    double c = s.nextDouble();

    double d = b * b - 4 * a * c;

    if (a == 0) { // если а=0, то уравнение решается линейно
      System.out.println("x=" + (-c / b));
    } else if (d < 0) {
      System.out.println("Нет корней");
    } else if (d == 0) {
      System.out.println("x=" + (-b / 2 / a));
    } else if (d > 0) {
      // формула корней: x1,2=(-b+-sqrtd)/2a
      System.out.println("x1=" + ((-b + Math.sqrt(d)) / 2 / a));
      System.out.println("x1=" + ((-b - Math.sqrt(d)) / 2 / a));
      //            System.out.println(Math.pow(6,2));
      // Math.pow - возводит число в степень
      // Вданном случае возводит 6 во вторую степень
    }
  }
Пример #11
0
  // Define main method for block program
  public static void main(String args[]) {

    // Define method to read keyboard input
    Scanner input = new Scanner(System.in);

    // Prompt user to input dimensions of block using Scanner. Saves dimensions
    System.out.println("Enter length of the block: ");
    double length = input.nextDouble();
    System.out.println("Enter width of the block: ");
    double width = input.nextDouble();
    System.out.println("Enter height of the block: ");
    double height = input.nextDouble();

    // Calculates volume
    double volume = length * width * height;

    // Calculates Surface Area
    double SA = 2 * (length * width + length * height + width * height);

    // prints volume and surface area
    System.out.println(
        "The volume of the block is "
            + volume
            + " and the surface area of the block is "
            + SA
            + ".");
  } // matches main method
Пример #12
0
  public static void percents() {

    Scanner sc = new Scanner(System.in);
    System.out.print("Enter your bank deposit: ");
    double x = sc.nextDouble();
    double y = 0;

    while (y <= x) { // inability to enter the smaller final result

      System.out.print(
          "Enter the desired result from the contribution of: "); // there must be progress, not
                                                                  // regress;)
      y = sc.nextInt();
    }

    System.out.print("Enter the interest rate: ");
    double p = sc.nextDouble();

    int years = 0;
    double per = p / 100;
    int nx = (int) x;
    while (nx < y) {

      double percent = nx * per;
      x += percent;
      years++;
      nx = (int) x; // reject a penny, rounding to the smaller value. How does the bank;)
    }

    System.out.println("Salary of not less than " + y + " hryvnias through " + years + " years.");
    System.out.println("In particular " + nx + " hryvnias");
  }
Пример #13
0
  public static void main(String[] args) {
    double score;
    double curvePercentage;

    Scanner keyboard = new Scanner(System.in);

    System.out.println("Enter the student's raw numeric score: ");
    score = keyboard.nextDouble();

    System.out.println("Enter the curve percentage: ");
    curvePercentage = keyboard.nextDouble();

    // Create a CurvedActivity object
    CurvedActivity curvedExam = new CurvedActivity(curvePercentage);

    // Set the exam score
    curvedExam.setScore(score);

    // Display the rawScore
    System.out.println("The raw score is " + curvedExam.getRawScore() + " points");

    // Display the curved score.
    System.out.println("The curved scored is " + curvedExam.getScore());

    // Display the exam grade.
    System.out.println("The exam grade is " + curvedExam.getGrade());
  }
  public String handle(File directory) {
    File averageRMS = new File(directory, MAX_FIELD_TXT);

    if (!averageRMS.exists()) return null;

    try {
      List<String> lines = FileUtils.readLines(averageRMS);

      int count = 0;
      double rmsSum = 0.0;

      for (String line : lines) {
        if (!line.startsWith("%")) {
          Scanner scanner = new Scanner(line);
          scanner.nextDouble();
          rmsSum += scanner.nextDouble();
          count++;
        }
      }

      return "" + (rmsSum /= count);

    } catch (IOException e) {
      e.printStackTrace();
      return null;
    }
  }
Пример #15
0
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    while (in.hasNextDouble()) {
      double totalCable = in.nextDouble();
      int n = in.nextInt();

      // Get vertices
      Map<String, Integer> map = new HashMap<String, Integer>();
      for (int i = 0; i < n; i++) {
        map.put(in.next(), i);
      }

      // Get edges
      Edge[] edges = new Edge[in.nextInt()];
      for (int i = 0; i < edges.length; i++) {
        Edge e = new Edge(map.get(in.next()), map.get(in.next()), in.nextDouble());
        edges[i] = e;
      }

      // Get MST length
      double cableLen = 0;
      for (Edge e : kruskals(n, edges)) {
        cableLen += e.weight;
      }

      if (Double.compare(totalCable, cableLen) < 0) {
        System.out.println("Not enough cable");
      } else {
        System.out.printf("Need %.1f miles of cable\n", cableLen);
      }
    }
  }
Пример #16
0
  /*
   * El ordenador de nuestro coche calcula los kilómetros que nos quedan antes de repostar. Crea un programa que pida:
   *  tamaño del depósito (en litros), porcentaje del depósito que está lleno y litros de consumo por 100kms.
   *  El programa mostrará los kilómetros que quedan de autonomía. Si quedan menos de 30 kilómetros mostrará un aviso
   *  de que hay que repostar porque estamos usando la reserva.
   */
  public static void main(String[] args) {

    Scanner teclado = new Scanner(System.in);

    double autonomia = 0;
    double litros = 0;

    System.out.println("Por favor introduzca la capacidad en LITROS de su depósito.");
    double depositoLitros = teclado.nextDouble();

    System.out.println(
        "Por favor introduzca (como NÚMERO REAL) el porcentaje del depósito ocupada por combustible");
    double depositoPorcentaje = teclado.nextDouble();

    System.out.println(
        "Por favor introduzca el consumo medio EN LITROS de combustible cada 100 Km");
    double consumoMedio = teclado.nextDouble();

    teclado.close();

    litros = depositoLitros * (depositoPorcentaje * 1 / 100);
    autonomia = (litros * 100) / consumoMedio;

    System.out.printf("La autonomia de su vehículo es de: %.2f Kilómetros %n%n", autonomia);

    if (autonomia < 30) {
      System.out.println("------------AVISO DE REPOSTAJE------------");
      System.out.println("Su autonomía es inferior a 30 Kilómetros");
    }
  }
 public void exec() throws Exception {
   DoubleObj a = new DoubleObj(), b = new DoubleObj(), c = new DoubleObj(), d = new DoubleObj();
   DoubleObj score = new DoubleObj();
   CharObj grade = new CharObj();
   output +=
       (String.format(
           "Enter thresholds for A, B, C, D\nin that order, decreasing percentages > "));
   a.value = scanner.nextDouble();
   b.value = scanner.nextDouble();
   c.value = scanner.nextDouble();
   d.value = scanner.nextDouble();
   output += (String.format("Thank you.  Now enter student score (percent) >"));
   score.value = scanner.nextDouble();
   if (score.value >= a.value) {
     grade.value = 'A';
   } else if (score.value >= b.value) {
     grade.value = 'B';
   } else if (score.value >= c.value) {
     grade.value = 'C';
   } else if (score.value >= d.value) {
     grade.value = 'D';
   } else {
     grade.value = 'F';
   }
   if (grade.value != 'F') {
     output += (String.format("Student has an %c grade\n", grade.value));
   } else {
     output += (String.format("Student has failed the course\n"));
   }
   if (true) return;
   ;
 }
Пример #18
0
  public void action() {

    System.out.println("Enter first number");
    Scanner sc = new Scanner(System.in);
    double firstNumber = sc.nextDouble();
    System.out.println("Enter second number");
    double secondNumber = sc.nextDouble();
    System.out.println("Enter action symbol");
    char action = sc.next().charAt(0);
    if (action == '/') {
      quotient = firstNumber / secondNumber;
      System.out.println(firstNumber / secondNumber);
    }
    if (action == '+') {
      sum = firstNumber + secondNumber;
      System.out.println(firstNumber + secondNumber);
    }
    if (action == '-') {
      difference = firstNumber - secondNumber;
      System.out.println(firstNumber - secondNumber);
    }
    if (action == '*') {
      product = firstNumber * secondNumber;
      System.out.println(firstNumber * secondNumber);
    }
  }
Пример #19
0
  public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    System.out.println("Insert your weight in pounds:");

    double weightPounds = input.nextDouble();

    System.out.println("Instert feet:");

    double heightFeet = input.nextDouble();

    System.out.println("Insert inches:");

    double heightInches = input.nextDouble();

    double weightKg = weightPounds * 0.45359237;
    double heightM = heightInches * 0.0254 + heightFeet * 0.3048;
    double bmi = weightKg / Math.pow(heightM, 2);

    System.out.println("Your BMI is " + bmi + ".");

    if (bmi >= 30.0) System.out.println("You're obese");
    else if (bmi > 25.0) System.out.println("You're overweight.");
    else if (bmi >= 18.5) System.out.println("Your weight is normal.");
    else System.out.println("You're underweight.");
  }
Пример #20
0
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    System.out.println("Enter your first name");
    String fname = input.next();

    System.out.println("Enter your last Name");
    String lname = input.next();

    System.out.println("Enter your gender ");
    String gender = input.next();

    System.out.println("Enter your month of birth");
    int month = input.nextInt();

    System.out.println("Enter your day of birth");
    int day = input.nextInt();

    System.out.println("Enter your year of birth");
    int year = input.nextInt();

    System.out.println("Enter your weight in kgs?");
    double weight = input.nextDouble();

    System.out.println("Enter your height metres");
    double height = input.nextDouble();

    HealthProfile prof = new HealthProfile(fname, lname, gender, month, day, year, weight, height);

    prof.bmi();
    prof.age();
    prof.mhr();
    prof.thr();
  }
Пример #21
0
  public static void main(String[] args) {
    Scanner myScanner;
    myScanner = new Scanner(System.in);
    // Prompt the user for input

    System.out.print("Enter the original cost of the check in the form xx.xx: ");
    double checkCost = myScanner.nextDouble();

    System.out.print(
        "Enter the percentage tip that you wish to pay as a whole number (in the form xx): ");
    double tipPercent = myScanner.nextDouble();
    tipPercent /= 100;

    System.out.print("Enter the number of people who went out to dinner: ");
    int numPeople = myScanner.nextInt();

    double totalCost;
    double costPerPerson;
    int dollars, // whole dollar amount of cost
        dimes,
        pennies; // for storing digits
    // to the right of the decimal point
    // for the cost$
    totalCost = checkCost * (1 + tipPercent);
    costPerPerson = totalCost / numPeople;
    // get the whole amount, dropping decimal fraction
    dollars = (int) costPerPerson;
    // get dimes amount, e.g.,
    // (int)(6.73 * 10) % 10 -> 67 % 10 -> 7
    //  where the % (mod) operator returns the remainder
    //  after the division:   583%100 -> 83, 27%5 -> 2
    dimes = (int) (costPerPerson * 10) % 10;
    pennies = (int) (costPerPerson * 100) % 10;
    System.out.println("Each person in the group owes $" + dollars + "." + dimes + pennies);
  }
  public void bankAccount() {
    // declare variables
    double balance, deposit, withdrawal;
    int months;

    // prompt for starting balance
    System.out.print("Starting Balance: ");
    balance = sc.nextDouble();

    // loop through months
    months = 1;
    do {
      // input deposit and withdrawal
      System.out.format("\nMonth #%-5dDeposits: ", months);
      deposit = sc.nextDouble();
      if (deposit != -1) {
        System.out.format("%12sWithdrawals: ", " ");
        withdrawal = sc.nextDouble();

        // calculate new balance
        balance += deposit;
        balance -= withdrawal;
        months++;
      }
    } while (balance >= 0 && deposit != -1);

    // output final balance
    System.out.format("\nYou have $%.2f left.", balance);

    // catch extra return
    sc.nextLine();
  }
 public TrainingData(String filePath) throws IOException {
   System.out.println("Starting Reading Data");
   Scanner st = new Scanner(new BufferedReader(new FileReader(filePath)));
   this.numberOfSamples = st.nextInt();
   int originalFeatures = st.nextInt();
   int extraFeatures = (originalFeatures * (originalFeatures - 1)) / 2;
   this.numberOfFeatures = originalFeatures + extraFeatures;
   X = new double[numberOfSamples][1 + numberOfFeatures];
   y = new double[numberOfSamples];
   average = new double[1 + numberOfFeatures];
   range = new double[1 + numberOfFeatures];
   for (int i = 0; i < numberOfSamples; i++) {
     X[i][0] = 1;
     double numberOfFollowers = st.nextDouble();
     X[i][1] = numberOfFollowers;
     int j = 2;
     for (; j < 1 + numberOfFeatures - extraFeatures; j++) {
       X[i][j] = st.nextDouble();
     }
     for (int k = 1; k <= originalFeatures; k++) {
       for (int l = k + 1; l <= originalFeatures; l++) {
         X[i][j++] = X[i][k] * X[i][l];
       }
     }
     y[i] = st.nextDouble();
   }
   System.out.println("Done Reading Data");
   System.out.println("Starting Normalization");
   normalizeFeatures();
   System.out.println("Done Normalizing Data");
 }
Пример #24
0
 public void parseExpression(String expression) {
   this.expression = expression;
   input = new Scanner(this.expression);
   var1 = input.nextDouble();
   operation = input.next();
   var2 = input.nextDouble();
 }
Пример #25
0
  public static void main(String[] args) {

    Scanner input = new Scanner(System.in); // Creates a scanner

    double numb1; // First Number input
    double numb2; // Second Number input
    double numb3; // Third Number input
    double sum; // Sum of numb1, numb2 and numb3
    double avg; // Final Average

    System.out.print("Enter the first integer:"); // Asks user for first number
    numb1 = input.nextDouble(); // Reads the fist number from the user

    System.out.print("Enter the second integer:"); // Asks user for the second number
    numb2 = input.nextDouble(); // Reads the second number from the user

    System.out.print("Enter the third integer:"); // Asks user for the third number
    numb3 = input.nextDouble(); // Reads the third number from the user

    sum = numb1 + numb2 + numb3; // adds all the numbers and is stored in sum

    avg = sum / 3; // Takes the average of all three numbers and stores in avg

    System.out.printf("The final average of the integers is %g\n", avg); // displays the average
  } // end method main
Пример #26
0
  public static void main(String[] args) {
    // initial values
    double accountBalance = 2555.75;
    double accountDeposit;
    double accountWithdrawal;
    int userChoice;

    // Scanner object for user input
    Scanner scnr = new Scanner(System.in);

    // Prompt user to enter transaction type of Balance, Deposit, or Withdrawal
    System.out.println("Welcome to Bank of Belgrade");
    System.out.println("Your initial account balance is " + accountBalance);
    System.out.println("Enter your choice of transaction: ");
    System.out.println("1. Withdraw Funds");
    System.out.println("2. Deposit Funds");
    System.out.println("3. Account Balance");

    userChoice = scnr.nextInt();

    // Few options to choose
    switch (userChoice) {
        // case for withdrawing amounts
      case 1:
        System.out.println("Enter amount for withdrawal: ");
        accountWithdrawal = scnr.nextDouble();
        if (accountWithdrawal > accountBalance) {
          System.out.println("Insufficient funds");
        } else {
          accountBalance = accountBalance - accountWithdrawal;
          System.out.println("Your current balance is " + accountBalance);
        }
        break;

        // case for depositing amounts
      case 2:
        System.out.println("Enter amount that you want to deposit ");
        accountDeposit = scnr.nextDouble();
        if (accountDeposit <= 0) {
          System.out.println("You must deposit an amount greater than 0");
        } else {
          accountBalance = accountBalance + accountDeposit;
          System.out.println("Your current balance is " + accountBalance);
        }

        break;

        // case for checking your balance
      case 3:
        System.out.println("Your balance is " + accountBalance);

        break;

        // default for preventing endless looping
      default:
        System.out.println("Incorrect Choice Human, Goodbye");

        break;
    }
  }
  public static void main(String[] args) {
    // Create scanner object.
    Scanner input = new Scanner(System.in);

    // Input
    System.out.print(
        "Please enter one side of your right triangle that is not " + "the hypotenuse: ");
    double number1 = input.nextDouble();
    System.out.print(
        "Please enter the other side of your right triangle that " + "is not the hypotenuse: ");
    double number2 = input.nextDouble();

    // Calculation.
    double calc1 = (number1 * number1) + (number2 * number2);
    double hypotenuse = Math.sqrt(calc1);

    // Output
    System.out.println(
        "The square of "
            + number1
            + " + the square of "
            + number2
            + " equals "
            + calc1
            + " which is the square of "
            + hypotenuse
            + ", which is the hypotenuse.");
  }
Пример #28
0
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the sides of Triangle: ");
    double a = sc.nextDouble();
    double b = sc.nextDouble();
    double c = sc.nextDouble();

    Triangle tri1 = new Triangle(a, b, c);
    double res = tri1.area();
    if (a + b > c && b + c > a && c + a > b) {
      System.out.println("The area of triangle is: " + res);
    } else {
      System.out.println("This is not Triangle!");
    }

    System.out.println("Enter the sides of another Triangle: ");
    double e = sc.nextDouble();
    double f = sc.nextDouble();
    double g = sc.nextDouble();
    Triangle tri2 = new Triangle(e, f, g);
    res = tri2.area();
    if (a + b > c && b + c > a && c + a > b) {
      System.out.println("The area of another triangle is: " + res);
    } else {
      System.out.println("This is not Triangle!");
    }
    sc.close();
  }
Пример #29
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 + "\" не поддерживается.");
    }
  }
Пример #30
0
  public static void decideOnShape(String shape) {
    Scanner myScanner = new Scanner(System.in);

    double area = 0;
    if (shape.equals("rectangle")) {
      // ask important things, then run correct calc.
      System.out.println("What is the width?");
      double width = myScanner.nextDouble();
      System.out.println("What is the hight?");
      double hight = myScanner.nextDouble();
      area = rectArea(width, hight);
    } else if (shape.equals("triangle")) {
      // ask important things, then run correct calc.
      System.out.println("What is the bade length?");
      double width = myScanner.nextDouble();
      System.out.println("What is the hight?");
      double hight = myScanner.nextDouble();
      area = triArea(width, hight);
    } else {
      // ask important things, then run correct calc.
      System.out.println("What is the radius?");
      double radius = myScanner.nextDouble();
      area = cirArea(radius);
    }
    System.out.println("The area is " + area);
  }