Is there a faster/simpler way of constructing objects from scanned inputs - java

Imagine you want to create an unknown amount of instances of a class. You decide to use an ArrayList (if there is a better option I would very much appreciate if someone could explain this) You want to allow instances of the class to be created through the System Input.
import java.util.ArrayList;
import java.util.Scanner;
class MyClass {
static ArrayList<MyClass> myArrayList = new ArrayList<>();
int field1;
int field2;
int field3;
public MyClass(int field1, int field2, int field3) {
// contructor statements
}
Here is the problem, if you scan inputs, you cannot feed them into the constructor, as you need to print messages in between and then scan the input. You are forced to store the values of all the fields by assigning them to other variables as shown below, you can also set the fields at the index of the new object each time you scan them, but this seems like it would be slow and complicated code.
static void createNewInstance() {
Scanner myScanner = new Scanner(System.in);
System.out.println("Enter field 1");
int f1 = myScanner.nextInt();
System.out.println("Enter field 2");
int f2 = myScanner.nextInt();
System.out.println("Enter field 3");
int f3 = myScanner.nextInt();
myArrayList.add(new MyClass(f1, f2, f3));
}
}
So I am wondering if there is a way to pass the scanned input directly into the constructor, it seems like storing the values as variables would take a bit of computation and also, if these variables are primitive, i think they would be in stack, which stack has static memory allocation, so they are permanently there. It seems to me like on a large scale, this is not such a great solution, but I am also extremely limited in my knowledge of program performance, so I am not exactly sure. I am guessing the answer is just use that solution, any others are just too complicated to be worth using. Thank you for reading, sorry I have struggled to word this question in a concise way.

In "normal" situation you will never create objects like this - there are many many ways the application receiving objects (reading from batch, receiving HTTP requests, deserialization...) and I never saw "on production" prompting the user "now give me the value of the first field..." etc and scanning values
it seems like storing the values as variables would take a bit of computation
and that's not a problem at all - creating objects in Java is super fast, additional three primitive fields are not relevant at all when it comes to the performance
Don't overengineer this

Firstly, lets mention that Premature Optimization Is the Root of All Evil
Having mentioned that, if you still want to get your user input through the stdin, you could asks your user to provide his numbers at once.
e.g
"Provide your numbers seperated by ,"
And then, after using scanner.nextLine() you can split the line and get your numbers (and validate that all 3 numbers were given).

Builder pattern and optionally Project Lombok are your friends!
public static void main(String[] args) {
MyClass obj = createNewInstance();
}
public static MyClass createNewInstance() {
Scanner scan = new Scanner(System.in);
MyClass.MyClassBuilder builder = MyClass.builder();
builder.field1(scan.nextInt());
builder.field2(scan.nextInt());
builder.field3(scan.nextInt());
return builder.build();
}
#Builder
#RequiredArgsConstructor
public static class MyClass {
private final int field1;
private final int field2;
private final int field3;
}
Another option is to put Scanner directly to the constructor (but this is NOT GOOD from Object Design Principles)
public static void main(String[] args) {
MyClass obj = new MyClass(new Scanner(System.in));
}
public static class MyClass {
private final int field1;
private final int field2;
private final int field3;
public MyClass(Scanner scan) {
field1 = scan.nextInt();
field2 = scan.nextInt();
field3 = scan.nextInt();
}
}

Related

why doesn't the variable increase?

I am learning Java, so I understand this is a very simple question, but I still want to understand it.
I want to let my code automatically generate soldiers, and the number automatically increases, but I failed.
the Soldier.class:
package com.mayer;
import java.util.Random;
public class Soldier {
private int number=0;
private int ATK;
private int HP;
Random ra = new Random();
public Soldier(){
this.number++;
this.ATK = ra.nextInt(10)+90;
this.HP = ra.nextInt(20)+180;
}
public void report(){
System.out.println("number:"+this.number+"\t"+
"ATK:"+this.ATK+"\t"+
"HP:"+this.HP);
}
}
the main.class
package com.mayer;
public class Main {
public static void main(String[] args) {
Soldier[] soldiers = new Soldier[5];
int i = 0;
while(i<5){
soldiers[i] = new Soldier();
i++;
}
for(Soldier sol:soldiers){
sol.report();
}
}
}
That's what I get:
number:1 ATK:94 HP:187
number:1 ATK:94 HP:181
number:1 ATK:96 HP:193
number:1 ATK:90 HP:183
number:1 ATK:95 HP:193
So you see,each of this number is 1.
You have added number field which is instance field. It will initialize per instance. You are looking for static type variable. Please check static into java.
Instance Variables (Non-Static Fields) Technically speaking, objects
store their individual states in "non-static fields", that is, fields
declared without the static keyword. Non-static fields are also known
as instance variables because their values are unique to each instance
of a class (to each object, in other words); the currentSpeed of one
bicycle is independent from the currentSpeed of another.
Class Variables (Static Fields) A class variable is any field declared with the static modifier; this tells the compiler that there
is exactly one copy of this variable in existence, regardless of how
many times the class has been instantiated. A field defining the
number of gears for a particular kind of bicycle could be marked as
static since conceptually the same number of gears will apply to all
instances. The code static int numGears = 6; would create such a
static field. Additionally, the keyword final could be added to
indicate that the number of gears will never change.
The constructor is changed to:
public Soldier(int number){
this.number = number;
this.ATK = ra.nextInt(10)+90;
this.HP = ra.nextInt(20)+180;
}
As others have said, each Soldier instance has its own separate number field which starts with 0. You can use a static field to count the instances:
public class Soldier {
private static int counter = 0;
private int number;
// other fields left out for clarity
public Soldier(){
Soldier.counter++; // field shared among all Soldier instances
this.number = counter; // number belongs to this instance only
// ...
}
// ...
}
However, I wouldn't recommend doing it this way. When you get more advanced, you'll learn that using a static field like this can cause problems in a multi-threaded application. I would instead advise passing the number to the Soldier constructor:
public class Soldier {
private int number;
// ...
public Soldier(int number){
this.number = number;
// ...
}
// ...
}
And then:
public static void main(String[] args) {
Soldier[] soldiers = new Soldier[5];
int i = 0;
while(i<5){
soldiers[i] = new Soldier(i);
i++;
}
Soldier.class
all-uppercase field names tend to be used for constants.. basic fields use headless camel-case.. They should also be descriptive, i.e. you should look at them an it should be apparent what they represent - for example a variable "number" is not a good idea, because it's ambiguous
Random can be converted to a local variable, no need to keep it on the class level
The mechanism by which soldiers are assigned IDs should be on a higher level - it can't be managed by the soldier object itself, hence the constructor with an argument
overriding the toString method is the traditional way of transforming the object to string for debugging purposes.. also most IDEs can generate it with a press of a button so no space for human error
You will obviously need getters and setters for your variables, if you wish to read or change them from elsewhere, but I don't think that's necessary to post here.
private int soldierID;
private int attack;
private int health;
public Soldier(int id){
this.soldierID = id;
Random random = new Random();
this.attack = random.nextInt(10) + 90;
this.health = random.nextInt(20) + 180;
}
#Override
public String toString() {
return "Soldier{" +
"soldierID=" + soldierID +
", attack=" + attack +
", health=" + health +
'}';
}
Main.class
it's perfectly fine and actually preferred to use a List instead of an array, because it's more comfortable to work with
this way it's even much easier to add them dynamically and use the iterator for ID
you can "report" in the creation cycle
This even shortens the method a bit, not that it's that important here.
public static void main(String[] args){
List<Soldier> soldiers = new ArrayList<>();
for(int i=0; i<5; i++){
Soldier newSoldier = new Soldier(i);
soldiers.add(newSoldier);
System.out.println(newSoldier.toString());
}
}
This way when you define the soldier IDs it's not from within the Soldier class but rather from something that is "observing" all the soldier classes and knows which is which.

How do I make a constructor that assigns multiple parameters?

I am really new to java and just trying to get my head around how everything works. I have a method like this:
public assignmentmarks(String name, int mark1, int mark2, int mark3)
{
}
and the question asks to create the constructor that uses all the fields (courseName, assignment1, assignment2, assignment3)
This is what I have tried
import java.util.Scanner;
public class assignmentmarks {
private String courseName;
private int assignment1;
private int assignment2;
private int assignment3;
int average;
int mark;
Scanner scanner = new Scanner(System.in);
public void AssignmentMarks(String name, int mark1, int mark2, int mark3)
{
assignment1 = mark1;
assignment2 = mark2;
assignment3 = mark3;
courseName = name;
AssignmentMarks assignmentMarks = new AssignmentMarks(mark1, mark2, mark3, name);
}
I have a method like this:
public assignmentmarks(String name, int mark1, int mark2, int mark3)
{
}
That is not a method. It is a constructor!!
A constructor is a "method-like thing" that has no return type, and the same name as the enclosing class.
All you need to do is add some statements that will assign the parameters to the fields of your class.
Having said that, assignmentmarks is a bad choice for a class name. The Java style rules say that a class name should:
Start with a capital letter
Use camel case; i.e. each embedded word should start with a capital letter.
Thus ... AssignmentMarks would be a better name.
(Yes ... this kind of stuff really does matter. Conforming to standard style makes your code readable, which makes it more maintainable, which will save you and your future colleagues time and hair-tearing.)
Also note the names (identifiers) in Java are case sensitive. So you need to be consistent. Don't use assignmentmarks in one place and AssignmentMarks in another. That is likely to lead to compilation errors ... or worse.
There are few ways to go around that.
Firstly the thing you aimed to create is called an "All-arguments-constructor" meaning you want to have a declared way to create an instance(entity) of a class and while doing so you want to have all properties(fields\parameters) of it filled with values specified on the call of the said constructor.
There is a hack way to do so using lombok and just annotating your class with #AllArgsConstructor, but I recommend you continue learning how those things are made by hand and then revisit mentioned syntaxis sugar later.
With that being said you want to create something like a method that neither has return type nor "void" written in its signature, then refers to every property(field\parameter) of an instance trough this (which literally means "I want to work with this particular entity") and then assigns them values that you passed through constructor.
In your case, it would look like that:
// We have passed all the values that we need trough constructor.
public AssignmentMarks(String name, int ass1, int ass2, int ass3, int mark, int average) {
// Now we assign them to the properties of an instance we creating.
// "courseName" of the created instance becomes "name" we passed.
this.courseName = name;
// "assignment1" of the created instance becomes "ass1" we passed
this.assignment1 = ass1;
// I bet you are getting the hang of it now.
this.assignment2 = ass2;
// And so on.
this.assignment3 = ass3;
// And so forth.
this.mark = mark;
// Until you have assigned values to all properties you want to assign in the constructor.
this.average = average;
}
Now that you have this constructor you could just simply create a new instance like so:
AssignmentMarks instance = new AssignmentMarks("programming", 1, 2, 3, 17, 20);
Where we also declared all the values we want to be assigned.
This how you could have done it with lombok:
//This is an entire class
#AllArgsConstructor
public class AssignmentMarks {
private String courseName;
private int assignment1;
private int assignment2;
private int assignment3;
int average;
int mark;
}
Now it already has "All argument constructor" because of #AllArgsConstructor annotation.
P.S. I double the previous writer on naming your class in CamelCase it is important.

Where to put methods scanner concretely(Java)

so my question is very short, I have a java constructor, and a java class that has to use the constructor to build an object.I need to ask the user for arguments that are required to build the object.Normally, do I put the required scanner(to make user input arguments) in the correct constructor methods or I ask these directly in the class methods thats use the constructor?For example, having construc.java(wich is the constructor)and contains methods like:¸
public void setNumber(int JNumber){
if(JNumber>=0){
Number = JNumber;
and a file called caller.java thats contain methods like:
public void add();
construc test = new construc(string,int,int,string,string); //instance to use the constructor methods
So basically im wondering where to put this code part that ask for the number to assign the the object:
Scanner thenum = new Scanner(System.in);
System.out.print("Entrez la quantité: \n");
int ob1num = thenum.nextInt();
ob1num = JNumber;
setNumber(JNumber);
I am a little bit confuse in Java(and beginner).Thank you!
This depends on how you want to use your setNumber() method. If you also want to use it to set numbers that are not based on the users input, putting the Scanner outside of the method is advised. Personally I would have the Scanner outside of the method to make which would make the method more versatile. If you need to scan multiple numbers, maybe put the scanning part in its own method that returns an int based on the users input.
class YourClass {
YourClass() {
//Initialize
setNumber();
}
}
public static main(String[] args) {
//Create new YourClass object and set value from user input
YourClass object = new YourClass();
}
With getter and setter methods available in the MyClass.Your main class methods can read values
Scanner thenum = new Scanner(System.in);
System.out.print("Entrez la quantité: \n");
int ob1num = thenum.nextInt();
And pass value to constructor
MyClass(int JNumber,String JString){
this.JNumber = JNumber;
this.JString = JString;
}

Running totals to work throughout classes in java?

I am current writing a program that includes a test. When the user clicks submit it either prints out correct or incorrect and then goes to a different class. As well as doing this i want if the answer is correct to add 1 to a variable.
The thing i can't work out is how to do this in different classes since 1 or 0 will need to be added for everything question which are saved in different classes but in the same project.
Is there any reason that each question is a separate class? It seems that you could have a single Question class which hold instance variables, such as
public class Question{
private String text; //the question itself
private String[] choices; //the choices if this is a multiple-choice question
private int answer; //the index in choices that is the correct answer
//constructor, accessors, mutators
public String toString(){
String retval = this.text+"\n";
for(int x=0;x<choices.length;x++){
char c = 'a'+x; //this will give characters going alphabetically from 'a'
retval+=c+") "+choices[x]+"\n";
}
return retval;
}
}
Then you could have a Test class with the main method.
public class Test{
public static void main(String args[]){
Question[] questions = {
new Question("What is 1+1?", new String[]{"2", "3", "4"}, 0),
//other questions here
}
int total=0;
Scanner input = new Scanner(System.in);
for(Question q: questions){
System.out.println(q.toString());
int ans = input.nextLine().charAt(0)-'a';
if(q.getAnswer()==ans){
total++;
}
}
}
}
Does this sort of do what you want?
This counter does not have a context within each of the individual classes. It only has context within the code you have managing these tests you are running. So, within this manager class, you have one variable that you increment each time a test completes and you detect it to be correct.
You want a different class with a public final static class and variable.
Something like this:
public class Counter {
private static int count=0;
public static int add() {
return count++;
}
}
You may want a getter as well.
Whatever class has a reference to the questions should loop through them and sum up a total of correct questions. If your questions don't inherit from the same class create an interface named Question that has a isAnswerRight() method that you can call, or something similar.

Counter that will remember its value

I have a task to operate on complex number. Each number consists of double r = real part, double i = imaginary part and String name. Name must be set within constructor, so I've created int counter, then I'm sending its value to setNextName function and get name letter back. Unfortunately incrementing this 'counter' value works only within costructor and then it is once again set to 0. How to deal with that?Some constant value? And second problem is that I also need to provide setNextNames(char c) function that will change the counter current value.
The code :
public class Imaginary {
private double re;
private double im;
private String real;
private String imaginary;
private String name;
private int counter=0;
public Imaginary(double r, double u){
re = r;
im = u;
name = this.setNextName(counter);
counter++;
}
public static String setNextName(int c){
String nameTab[] = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N",
"O","P","Q","R","S","T","U","W","V","X","Y","Z"};
String setName = nameTab[c];
System.out.println("c: "+c);
return setName;
}
public static String setNextName(char c){
//
//don't know how to deal with this part
//
}
It's hard to tell what you're doing, but I suspect this will solve your immediate problem:
private static int counter = 0;
You should make counter static.
You should also make nameTab a private static field, then in setNextName(), you can iterate through it to find the name corresponding to the given character, and get its index. (in the plain ASCII world, of course one could simply calculate the index by subtracting the numeric value of 'A' from the given character, but I am not quite sure how it would work out with Java, in Unicode, with crazy inputs - iteration is on the safe side.)
In OO languages there are typically two types of variables that go into a class:
instance variables that are unique to each instance
class variables that are shared by all instances of the class
Given a class like:
public class Person
{
// class variable
private static int numberOfEyes;
// instance variable
private String name;
// other code goes here
}
If you were to do something like:
Person a = new Person("Jane Doe");
Person b = new Person("John Doe");
and then do something like:
a.setName("Jane Foe");
the name for Person "a" would change, but the one for Person "b" would stay the same.
If you woke up one morning and decided you wanted 3 eyes:
Person.setNumberOfEyes(3);
then Person "a" and Person "b" and every other Person instance out there would suddenly have 3 eyes as well.
You want to put "static" in your counter declaration.
is your code being used by multiple threads than i would suggest that making counter static won't solve ur problem.
you need to take extra care by implementing thread synchronization use lock keyword as shown below.
private static readonly obj = new Object();
private static int counter =0;
public Imaginary(double r, double u)
{
re = r;
im = u;
lock(obj)
{
name = this.setNextName(counter);
counter++;
}
}
this will ensure thread safety also while incrementing your counter (there are another ways also to provide thread security but this one is having least code).
Because the field counter is not static, every object has its own counter.

Categories