PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, October 30, 2022

[FIXED] How to save stdin data into class/object [JAVA]

 October 30, 2022     class, eof, java, java.util.scanner, object     No comments   

Issue

I want to use a Class to hold user inputs. For example "example_name";"example_value";"example_city" is the form of the input and I want to make objects from an input stream of theese three inputs line by line from a file. So whenever I enter Adam;27; London it should be saved into an Object(Adam,27,London) and ask for the next input. Thank you for your help, I know this might be a stupid question but I'm new to OO programming and I have a C background and don't want to use two dimensional arrays.


Solution

Let's break this problem into 3 section. First, we will have to design the class. Second, we will take the user input and create an object of that class until the user press n(no). Third, we will display the user information. Here I have used a LinkedList data structure for storing the inputs.

Section 1:

class example{

   String example_name; 
    int example_value;
    String example_city;
    example(String name,int value,String city)
    {
        this.example_name = name;
        this.example_value = value;
        this.example_city = city;
    }
}

section 2:

 LinkedList<example> ob = new LinkedList<>();
        Scanner input = new Scanner(System.in);

        System.out.println("Press y to Continue n to Exit");
        char i = input.next().charAt(0);
        while(i!='n')
        {
            input.nextLine();
            System.out.println("Enter name");
            String name = input.nextLine();
            System.out.println("Enter value");
            int value = input.nextInt();
            input.nextLine();
             System.out.println("Enter city");
            String city = input.nextLine();
            ob.addLast(new example(name,value,city));
            System.out.println("Press y to Continue n to Exit");
             i = input.next().charAt(0);
        }

Section 3:

 for(example x:ob)
             System.out.println(x.example_name + " " + x.example_value + " "+x.example_city);


Answered By - suvojit_007
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing