Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 9 of 9

Thread: NullPointerException

  1. #1
    Junior Member
    Join Date
    Jan 2022
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default NullPointerException

    package Interfaces.InternetShop;
     
    import java.io.IOException;
    import java.util.Objects;
    import java.util.Scanner;
    import java.util.concurrent.TimeUnit;
     
    public class HelloKitty {
     
        public static class colors {
            public static final String reset = "\u001B[0m";
            public static final String black = "\u001B[30m";
            public static final String red = "\u001B[31m";
            public static final String green = "\u001B[32m";
            public static final String yellow = "\u001B[33m";
            public static final String blue = "\u001B[34m";
            public static final String purple = "\u001B[35m";
            public static final String cyan = "\u001B[36m";
            public static final String white = "\u001B[37m";
        }
     
        public static class User {
            private final String login;
            private final String password;
     
            private User(String user, String password) {
                this.login = user;
                this.password = password;
            }
     
            public Basket purchased;
     
            private String getLogin() {
                return login;
            }
     
            private String getPassword() {
                return password;
            }
        }
     
        public static class ProductHelloKitty {
            String modelName;
            double price;
     
            public ProductHelloKitty(String modelName, double price) {
                this.modelName = modelName;
                this.price = price;
            }
        }
     
        public static class CategoryHelloKitty {
            String nameCategory;
            ProductHelloKitty[] productHelloKitties;
     
            public CategoryHelloKitty(String nameCategory, ProductHelloKitty[] productHelloKitties) {
                this.nameCategory = nameCategory;
                this.productHelloKitties = productHelloKitties;
            }
        }
     
        public static class Basket {
            ProductHelloKitty[] purchased;
     
            public Basket(ProductHelloKitty[] purchased) {
                this.purchased = purchased;
            }
        }
     
        public static void Buy() {
            Basket cards = new Basket(card);
            client.purchased = cards;
            System.out.println("Товарный чек");
            for(int i = 0; i < client.purchased.purchased.length; ++i) {
                if(client.purchased.purchased[i] == null) break;
                System.out.println((i+1) + ". " + client.purchased.purchased[i].modelName + " ------- "
                        + client.purchased.purchased[i].price);
            }
            double gc = getCash(client.purchased.purchased);
            System.out.print("Общая сумма покупок составляет -------" + gc);
     
        }
     
        public static double getCash(ProductHelloKitty[] p) {
            double cash = 0.0;
            for(int i = 0; i < p.length; ++i) {
                if(p[i] == null) break;
                cash+=p[i].price;
            }
            return cash;
        }
     
        public static void getBasket(ProductHelloKitty[] product) throws InterruptedException {
            for (int i = 0; i < product.length; i++) {
                if (product[i] == null) break;
                System.out.println((i+1) + ". " + product[i].modelName + " " + product[i].price + "UAH");
            }
            System.out.println("0. Назад");
            Scanner scanner = new Scanner(System.in);
            System.out.println("");
            int number = scanner.nextInt();
            System.out.println("");
            if (number == 0) getMenu();
        }
     
        public static void seeProduct(CategoryHelloKitty hk) throws InterruptedException {
            for (int i = 0; i < hk.productHelloKitties.length; i++) {
                System.out.println((i+1) + ". " + hk.productHelloKitties[i].modelName + " " + hk.productHelloKitties[i].price + "UAH");
            }
            System.out.println("0. Назад");
            Scanner scanner = new Scanner(System.in);
            System.out.println("");
            int number = scanner.nextInt();
            System.out.println("");
            if (number == 0) getMenu();
            else buyProduct(hk.productHelloKitties[number -1]);
        }
     
        public static void buyProduct(ProductHelloKitty product) throws InterruptedException {
            System.out.println("");
            System.out.println(colors.red + "Продукт " + product.modelName + " " + product.price + "UAH был добавлен в корзину" + colors.reset);
            System.out.println("");
            for (int i = 0; i < card.length; i++) {
                if (card[i] == null) {
                    card[i] = product;
                    break;
                } else {
                    if (i+1 == card.length && card[i] == null) {
                        System.out.println("Ваша корзина заполнена");
                        break;
                    }
                }
            }
            getCategory(all);
        }
     
        public static void getCategory(CategoryHelloKitty[] categoryHelloKitties) throws InterruptedException {
            for (int i = 0; i < categoryHelloKitties.length; i++) {
                System.out.println("#" + (i+1) + " " + categoryHelloKitties[i].nameCategory);
            }
            System.out.println("0. Назад");
            Scanner scanner = new Scanner(System.in);
            System.out.println("");
            int number = scanner.nextInt();
            System.out.println("");
            if (number == 0) getMenu();
            else seeProduct(all[number - 1]);
        }
     
        public static void Sleep() throws InterruptedException {
            TimeUnit.SECONDS.sleep(2);
        }
     
        public static void Redirect() {
            for (int i = 0; i < 200; i++) {
                System.out.println();
            }
        }
     
        private static void isAuth() throws InterruptedException, IOException {
            User user = new User("1", "2");
            Scanner scanner = new Scanner(System.in);
            System.out.println("Введите логин и пароль.\n");
     
            String userLogin = user.getLogin();
            String userPassword = user.getPassword();
     
            System.out.print("Логин: ");
            String userInputLogin = scanner.nextLine();
            System.out.print("Пароль: ");
            String userInputPassword = scanner.nextLine();
     
            if (Objects.equals(userLogin, userInputLogin) && Objects.equals(userPassword, userInputPassword)) {
                System.out.println("\nУспешно!");
                Sleep();
                System.out.println("\nПеренаправляем на сайт...");
                Sleep();
                Redirect();
            } else {
                System.out.println("Логин или пароль введены не верно.");
                System.exit(0);
            }
        }
     
        public static void getMenu() throws InterruptedException {
            System.out.println("Добро пожаловать в Hello Kitty/Melody магазин!\n");
            System.out.println("1.Каталог");
            System.out.println("2.Корзина");
            System.out.println("3.Оплатить");
            System.out.println("0.Выйти");
            Scanner scanner = new Scanner(System.in);
            System.out.println("");
            int number = scanner.nextInt();
            System.out.println("");
            switch (number) {
                case 1:
                    getCategory(all);
                    break;
                case 2:
                    getBasket(card);
                    break;
                case 3: {
                    Buy();
                    break;
                }
                case 0:
                    Redirect();
                    System.out.println("Будем рады если Вы зайдете к нам позже! <3");
                    Sleep();
                    System.exit(number);
            }
        }
     
        static ProductHelloKitty helloKitty1 = new ProductHelloKitty("Hello Kitty повар", 100);
        static ProductHelloKitty helloKitty2 = new ProductHelloKitty("Hello Kitty уборощица", 200);
     
     
        static ProductHelloKitty helloKitty3 = new ProductHelloKitty("Мелоди1", 300);
        static ProductHelloKitty helloKitty4 = new ProductHelloKitty("Мелоди2", 400);
     
        static ProductHelloKitty[] Type1 = {helloKitty1, helloKitty2};
        static ProductHelloKitty[] Type2 = {helloKitty3, helloKitty4};
     
        static CategoryHelloKitty type1 = new CategoryHelloKitty("Hello Kitty ассортимент", Type1);
        static CategoryHelloKitty type2 = new CategoryHelloKitty("Melody ассортимент", Type2);
     
        static CategoryHelloKitty[] all = {type1, type2};
        static ProductHelloKitty[] card;
     
        static User client;
     
        public static void main(String[] args) throws InterruptedException, IOException {
            card = new ProductHelloKitty[20];
            isAuth();
            getMenu();
        }
    }

    Compile
    write 1
    then write 2
    WAIT 4 SECONDS
    then write 3

    Why when I write 3, my code not working and show me error NullPointerException.

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: NullPointerException

    how me error NullPointerException.
    What statement does that happen on? What variable has the null value? If you can not tell, Add a print statement just before the statement that has the NPE to print out the values of all the variables used in the statement that has the NPE.
    Backtrack in the code to see Why that variable does not have a valid value?
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Jan 2022
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: NullPointerException

    Could you explain to me in more detail how I can fix the error? I do not understand

    --- Update ---

    I do
    System.out.println(client.purchased);

    And receive again error.

    --- Update ---

    So this variable is null, right? I need do client.purchased = 0; ?

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: NullPointerException

    What is the value in client when that statement is executed?
    If it is null, backtrack in the code to see why client does not have a valid value.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Jan 2022
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: NullPointerException

    But also I can't do this client.purchased = 0; So I don't know how to fix

    --- Update ---

    I already re-read the code, but I still can't figure out where my mistake is.

    --- Update ---

    public static void Buy() {
            Basket cards = new Basket(card);
            client.purchased = cards;
            System.out.println("Товарный чек");
            for(int i = 0; i < client.purchased.purchased.length; ++i) {
                if(client.purchased.purchased[i] == null) break;
                System.out.println((i+1) + ". " + client.purchased.purchased[i].modelName + " ------- "
                        + client.purchased.purchased[i].price);
            }
            double gc = getCash(client.purchased.purchased);
            System.out.print("Общая сумма покупок составляет -------" + gc);
     
        }

    I think problem is here. client.purchased = cards;

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: NullPointerException

    Where is the variable client assigned a value?
    client needs a valid value to keep from getting a NPE when it is used to reference an instance of a class.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Junior Member
    Join Date
    Jan 2022
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: NullPointerException

    Basket cards = new Basket(card);
    client.purchased = cards;

    I think here

    --- Update ---

    But I can't understand WHERE i need define

    --- Update ---

    I'm asked for help. Just tell me where I need fix. I'll understand later why I had to change the values there. Now we are playing with you the game "guess where it is wrong."

    Can you help me?

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: NullPointerException

    What value needs to be in the client variable?
    Where and when should that value be assigned to the client variable.

    I do not know what the code is supposed to be doing. There are no comments in English describing the purpose of the program.
    I can't suggest changes to the code without knowing what the code is supposed to do.
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Member
    Join Date
    Jan 2024
    Posts
    75
    Thanks
    0
    Thanked 4 Times in 4 Posts

    Default Re: NullPointerException

    The `NullPointerException` you're encountering when you input '3' is likely due to the `client` object being null. In your code, `client` is declared but never initialized. Hence, when you call the `Buy()` method which references `client`, it throws a `NullPointerException`.

    To fix this issue, you need to initialize the `client` object before calling `Buy()`. You can do this by instantiating a new `User` object and assigning it to `client` in your `isAuth()` method.

    Here's how you can modify your `isAuth()` method to initialize the `client` object:

    ```java
    private static void isAuth() throws InterruptedException, IOException {
    User user = new User("1", "2");
    Scanner scanner = new Scanner(System.in);
    System.out.println("Введите логин и пароль.\n");

    String userLogin = user.getLogin();
    String userPassword = user.getPassword();

    System.out.print("Логин: ");
    String userInputLogin = scanner.nextLine();
    System.out.print("Пароль: ");
    String userInputPassword = scanner.nextLine();

    if (Objects.equals(userLogin, userInputLogin) && Objects.equals(userPassword, userInputPassword)) {
    System.out.println("\nУспешно!");
    client = user; // Initialize the client object
    Sleep();
    System.out.println("\nПеренаправляем на сайт...");
    Sleep();
    Redirect();
    } else {
    System.out.println("Логин или пароль введены не верно.");
    System.exit(0);
    }
    }
    ```

    By initializing the client object in the isAuth() method, you ensure that it is not null when you call the Buy() method later in your code. This should resolve the NullPointerException issue. If you still encounter any challenges with your Java assignment, seeking assistance from resources like online assignment help platform like ProgrammingHomeworkHelp.com, online programming communities or educational platforms can provide valuable insights and support.

Similar Threads

  1. NullPointerException - don't know why
    By daniella in forum What's Wrong With My Code?
    Replies: 16
    Last Post: August 5th, 2019, 06:59 PM
  2. nullpointerexception bug
    By Jedi khan in forum What's Wrong With My Code?
    Replies: 7
    Last Post: July 11th, 2013, 09:01 AM
  3. [SOLVED] Nullpointerexception
    By kbwalker87 in forum What's Wrong With My Code?
    Replies: 7
    Last Post: October 14th, 2010, 10:33 PM
  4. [SOLVED] NullPointerException
    By javapenguin in forum What's Wrong With My Code?
    Replies: 13
    Last Post: October 1st, 2010, 12:10 AM
  5. NullPointerException
    By bbr201 in forum What's Wrong With My Code?
    Replies: 3
    Last Post: July 29th, 2010, 07:06 PM