Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Viikkoharjoitus 6, tehtävä 2.
- *
- * Lausekielinen ohjelmointi II, syksy 2019.
- *
- * Kalle Dalgamoni
- * 439880
- * kalle.dalgamoni@tuni.fi
- */
- import java.util.Scanner;
- public class Calculator {
- public static final Scanner lukija = new Scanner(System.in);
- /* määritellään komennot */
- public static final String SUMMAA = "add";
- public static final String EROTA = "diff";
- public static final String KERRO = "multi";
- public static final String JAA = "div";
- public static final String LOPETA = "quit";
- public static String[] tarkista(String komento) {
- /* luodaan tarkista metodi joka tarkistaa onko syöte komento
- ja onko sillä oikea määrä parametreja*/
- if (komento = null){
- return null;
- }else{
- String[] komennot = komento.split(" ");
- if (komennot.length == 3) {
- if (komennot[0].equals(SUMMAA) || komennot[0].equals(EROTA)) {
- return komennot;
- }
- else if (komennot[0].equals(KERRO) || komennot[0].equals(JAA)) {
- return komennot;
- }
- }
- else {
- return null;
- }
- }
- }
- public static void main(String[] args) {
- /*main metodissa tulostetaan*/
- boolean jatkuu = true;
- System.out.println("Hello! I am a simple calculator.");
- while (jatkuu) {
- System.out.println("Please, enter a command:");
- String komento = lukija.nextLine();
- if (komento.equals(LOPETA)) {
- jatkuu = false;
- }
- else {
- String[] laske = tarkista(komento);
- if (laske != null) {
- if (laske[0].equals(SUMMAA)) {
- System.out.println(Integer.parseInt(laske[1]) + Integer.parseInt(laske[2]));
- }
- else if (laske[0].equals(EROTA)) {
- System.out.println(Integer.parseInt(laske[1]) - Integer.parseInt(laske[2]));
- }
- else if (laske[0].equals(KERRO)) {
- System.out.println(Integer.parseInt(laske[1]) * Integer.parseInt(laske[2]));
- }
- else if (laske[0].equals(JAA)) {
- int apu2 = Integer.parseInt(laske[2]);
- if(apu2 != 0){
- System.out.println((float)(Double.parseDouble(laske[1]) / Double.parseDouble(laske[2])));
- }
- else{
- System.out.println("Error!");
- }
- }
- }
- else {
- System.out.println("Error!");
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement