Home > Software engineering >  How to store data from specific library in main application - Java
How to store data from specific library in main application - Java

Time:06-11

I'm very new learner in Java and currently having a hard time in understanding the concept of library and main. I'm trying to store the input of user in the specific library which is Store without adding "static". Is my logic wrong? Here's my code

    package app;
    import Library.*;
    import java.util.Scanner;

    public class Test {
        public static void main(String[] args) {
            System.out.println("Enter 1 if you want to store name data \nEnter 2 if you want to store age data ");

            Scanner scan = new Scanner(System.in);
            int choice = scan.nextInt();
            
            switch(choice){
                case 1:
                    System.out.printf("Name: ");
                    Store.name = scan.next();
                    break;
                    
                case 2:
                    System.out.printf("Age: ");
                    Store.age = scan.nextInt();
                    break;
            }   
        }

Heres my library code

    package library1;
    public class Store {
        public String name;
        public int age;
        public Store(String name, int age) {
            this.name = name;
            this.age = age;
        }
    }

CodePudding user response:

Since you haven't mentioned if you want to use switch case for same Store object, but if we assume its for same Store object, then you can do :

Store store=new Store("", 0); //initialize with no name & zero age.

switch(choice){
                case 1:
                    System.out.printf("Name: ");
                    store.name = scan.next();
                    break;
                    
                case 2:
                    System.out.printf("Age: ");
                    store.age = scan.nextInt();
                    break;
            }  

This will either set name or age but not both.

One more tip, import library.Store is required in your Test class.

  •  Tags:  
  • java
  • Related