С моим кодом у меня возникают проблемы с добавлением цикла в конец, чтобы код начинался заново

Это мой типичный код контроллера REST для запроса «получить пользователя по id»:

@RestController
@RequestMapping("/users") // 1
public class UserController {

    private final UserRepo userRepo;

    public UserController(UserRepo userRepo) {
        this.userRepo = userRepo;
    }

    @GetMapping("/{id}") // 2
    public ResponseEntity getById(@PathVariable("id") Long id) { // 3
        return userRepo.findById(id) // 4
                .map(UserResource::new) // 5
                .map(ResponseEntity::ok) // 6
                .orElse(ResponseEntity.notFound().build()); // 7
    }
}

Где:

1 - общий пусковой путь для всех запросов управляемый этим контроллером

2 - шаблон переменной пути запроса GET (/users/{id}).

3 - укажите имя переменной пути, имя которой соответствует параметру в GetMapping. Тип параметра в методе getById соответствует типу User ID.

4 - Я использую метод findById для моего UserRepo, который возвращает Optional

5 - Здесь я преобразовываю User в некоторый тип DTO - UserResource (это необязательный шаг)

6 - возвращает OK ответ, если User найдено

7 - или вернуть ответ Not Found в противном случае.

0
задан Hovercraft Full Of Eels 19 January 2019 в 17:26
поделиться

2 ответа

Хотя ответ, данный Сандом выше, является полностью правильным, учитывая количество используемых вами условий, которые не являются прямыми булевыми значениями, в конечном итоге будет быстрее и эффективнее использовать случай переключения, а также сохранять вам не нужно много печатать на современных компьютерах, это не должно быть проблемой, но тем не менее

import java.io.*;
import java.util.*;

public class addiePorterMod8Banking {
    public static void main(String args[]) {
        while (true) {
            int depositSavings, depositChecking, withdrawalSavings, withdrawalChecking, transferSavingsToChecking;
            int b, c, d, e, f, g, lp;
            int savingsaccount = 3000;
            int checkingaccount = 650;
            Scanner kbReader = new Scanner(System.in);
            System.out.println(
                    "What do you wish to do today?\n1 for deposit to savings\n2 for deposit to checking\n3 for withdraw from savings\n4 for withdraw from checking\n5 for transfer funds from savings to checking");
            int a = kbReader.nextInt();
            switch (a) {
            case (1):
                System.out.println("1-you chose to make a deposit to savings. How much would you like to deposit?");
                int answer = kbReader.nextInt();
                lp = savingsaccount + answer;
                System.out.println("Your total in savings is $" + lp);
                break;
            case (2):
                System.out.println("2-you chose to make a deposit to checking. How much would you like to deposit?");
                int answer1 = kbReader.nextInt();
                lp = checkingaccount + answer1;
                System.out.println("Your total in checking is $" + lp);
                break;
            case (3):
                System.out.println("3-you chose to withdraw from savings. How much would you like to withdraw?");
                int bunny = kbReader.nextInt();
                lp = savingsaccount - bunny;
                System.out.println("Your total in savings is $" + lp);
                break;
            case (4):
                System.out.println("4-you chose to withdraw from checking. How much would you like to withdraw?");
                int bubble = kbReader.nextInt();
                lp = checkingaccount - bubble;
                System.out.println("Your total in checking is $" + lp);
                break;
            case (5):
                System.out.println("5-Your current balance in savings is $3000. How much would you like to transfer?");
                int awesome = kbReader.nextInt();
                lp = savingsaccount - awesome;
                int al = checkingaccount + awesome;
                System.out.println("Your total in checking is $" + al + "." + "Your total in savings is $" + lp + ".");
                break;
            }
            System.out.println("Would you like another transaction? 1 for yes. 2 for No");
            int more = kbReader.nextInt();

            if (more == 2) {
                break;
            }
        }
    }
}

небольшое примечание на тот случай, если вы хорошо знакомы с делами коммутатора, вкратце, они похожи на длинные цепочка условных выражений, но как только одна задача выполнена, она не продолжает искать ее по всем значениям в виде последовательности операторов if, имеющих значение, как только что-то работает, она завершается вместо проверки каждого условия и для случаев, в которых нет Boolean считается быстрее читать дальше здесь

0
ответ дан Vugar Sadygov 19 January 2019 в 17:26
поделиться

Вы можете использовать цикл while, как показано ниже, и когда пользователь вводит 2, прервите его

import java.io.*;
import java.util.*;

public class Main {
    public static void addiePorterMod8Banking (String args[]) {
        while (true) {
            int depositSavings, depositChecking, withdrawalSavings, withdrawalChecking, transferSavingsToChecking;
            int b, c, d, e, f, g, lp;
            int savingsaccount = 3000;
            int checkingaccount = 650;
            Scanner kbReader = new Scanner(System.in);
            System.out.println("What do you wish to do today?\n1 for deposit to savings\n2 for deposit to checking\n3 for withdraw from savings\n4 for withdraw from checking\n5 for transfer funds from savings to checking");
            int a = kbReader.nextInt();
            if (a == 1) {
                System.out.println("1-you chose to make a deposit to savings. How much would you like to deposit?");
                int answer = kbReader.nextInt();
                lp = savingsaccount + answer;
                System.out.println("Your total in savings is $" + lp);
            }
            if (a == 2) {
                System.out.println("2-you chose to make a deposit to checking. How much would you like to deposit?");
                int answer = kbReader.nextInt();
                lp = checkingaccount + answer;
                System.out.println("Your total in checking is $" + lp);
            }
            if (a == 3) {
                System.out.println("3-you chose to withdraw from savings. How much would you like to withdraw?");
                int bunny = kbReader.nextInt();
                lp = savingsaccount - bunny;
                System.out.println("Your total in savings is $" + lp);
            }
            if (a == 4) {
                System.out.println("4-you chose to withdraw from checking. How much would you like to withdraw?");
                int bubble = kbReader.nextInt();
                lp = checkingaccount - bubble;
                System.out.println("Your total in checking is $" + lp);
            }
            if (a == 5) {
                System.out.println("5-Your current balance in savings is $3000. How much would you like to transfer?");
                int awesome = kbReader.nextInt();
                lp = savingsaccount - awesome;
                int al = checkingaccount + awesome;
                System.out.println("Your total in checking is $" + al + "." + "Your total in savings is $" + lp + ".");
            }
            System.out.println("Would you like another transaction? 1 for yes. 2 for No");
            int more = kbReader.nextInt();

            if (more == 2) {
                break;
            }
        }
    }
}
0
ответ дан Sand 19 January 2019 в 17:26
поделиться
Другие вопросы по тегам:

Похожие вопросы: