Okay, so I'm in java Object Oriented Programming and I'm stuck on one little thing on a project.
I have to create a class that holds a student name, calculates the total score and calculates the average score. But what's holding me up is that I need to create an object, that is called by the name that is given to me from input from the scanner.
I also am not 100% sure how to get the information from the program to the class, I think I just put them in the variable name from the name, but if I'm wrong, please tell me.
What I have so far is:
public class Prog2 {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
Student name = new Student();
System.out.println("Please enter the name of the student.");
String theName = input.nextLine();
name.setName(theName);
System.out.println();
System.out.printf("Name of the object is", name.getName());
}
}
Right now I want to see I I can get the name in there. I also need to name the project the same name as the name that's given to me.
It's not very clear what you are asking, you are asking how to create a student object and set that objects name field to the input given from the scanner?
One way to pass information from the program to the class is to create a constructor that sets the fields value upon object creation:
Student thisStudentObject = new Student(inputName, inputGrade)
Of course this is dependant upon the Student class having a contructor that matches those data types (in that order). for more information on constructors, see https://stackoverflow.com/a/19941847/4064652
Related
I am trying to make a method that will create a new unique object based on another class that I have have in the same project. I know that the last line wont compile, but is there a way to accomplish the same goal?
Ideally if the fName=John and lName=Smith, then the new "Employee" object created on the last line would be called "JohnSmith" but the goal is just to create a unique instance of the object every time that the method is called
public static void createEmployee(int number){
Scanner input= new Scanner(System.in);
System.out.printf("Enter first name for employee %s: ",number);
String fName=input.next();
System.out.printf("Enter last name for employee %s: ",number);
String lName=input.next();
Employee fName+lName= new Employee(fName,lName);
}
I am fairly new to Java, and object oriented programming in general so if I am going about this wrong I am open to going about it a different way.
No, what you're describing isn't possible.
As a conceptual exercise, your variables should describe the kind of data they're holding. It may sound pretty plain, but employee would be a better name for that variable than JohnSmith or SteveJobs or any other first + last name combination.
If you're intending to create a new instance of an Employee every time, you should return the Employee instance from the method instead of declaring it void. Then you can use it however you like wherever you call it.
public static Employee createEmployee(int number){
Scanner input = new Scanner(System.in);
System.out.printf("Enter full name of employee %d, separated by spaces: ", number);
String fName = input.next();
String lName = input.next();
return new Employee(fName, lName);
}
You can't do it that way. But remember, many "JohnSmith" exist - you would run into homonyms easily.
If these aren't a problem, you could use a Map to bind a key (The String made with Surname + Name) to a value (your employee).
Good luck and welcome to StackOverflow!
UPDATE
If homonyms are a problem, you will need to use unique IDs; they assure you that you have no overlaps. You could build an ID in the Employee itself, and put them in a List, or you can put them in an Array - the ID will then be their position in the array.
No. You can't combine a variable like that, but you could say something like
// Employee fName+lName= new Employee(fName,lName);
Employee employee = new Employee(fName, lName);
And if Employee overrides toString() then
System.out.println(employee);
should give you the output you would expect.
I second the hashmap. Having a human readable variable name dynamically created is overly complicated. Using a hashmap you can reference the object with a string
HashMap<String, Employee> employees = new HashMap<String, Employee>();
employees.put(fName + lName, new Employee(fName, lName));
To get the employ obj
employees.get(fName + lName);
so I have a program that ask(input) for stuff(variable int string etc..)and those elements are after that passed to the constructor.However, each time I input new values,previous are overwritten.How do I make it create a new one instead of overwritting the previous values?I am very new to Java and im kinda confuse.Heres my code:
Scanner scan1 = new Scanner(System.in); //user input the name
System.out.print("name: \n");
String name = scan1.nextLine();
and then pass it to the constructor:
Balloon aballoon = new Balloon(name);
my constructor looks like
public Balloon(String name){
setName(name);
and the method of it
public String thename
public void setName(String name){
if(name.matches("[a-zA-Z]+$")){
thename = name;
}
So yeah im wondering how to build multiple object(character) whitout overwritting the previous one,and how to store them(the character).
thank you
You can use an ArrayList<Balloon> to store multiple Balloon objects:
ArrayList<Balloon> baloons = new ArrayList<Balloon>;
//Read name
baloons.add(new Balloon(name));
//baloons now contains the baloon with the name name
For more information on how to use the ArrayList class, see Class ArrayList<E>.
I'd use a loop akin to something like the following to store all the balloons that the user wants:
List<Balloon> balloonList = new ArrayList<>();
Scanner input = new Scanner(System.in);
String prompt="Name?(Enter 'done' to finish inputting names)";
System.out.println(prompt); //print the prompt
String userInput=input.nextLine(); //get user input
while(!userInput.equals("done")){ //as long as user input is not
//"done", adds a new balloon
//with name specified by user
balloonList.add(new Balloon(userInput));
System.out.println(prompt); //prompt user for more input
userInput=input.nextLine(); //get input
}
For modify, I'm going to assume that you wish to find the balloon using its name(IE: If someone wants to delete/modify the balloon with the name "bob", it will delete/modify the (first) balloon in the ArrayList that has the name "bob".
For deletion, it is simple- write a a simple method to find the balloon specified(if it is in the list) and delete it.
public static boolean removeFirst(List<Balloon> balloons, String balloonName){
for(int index=0;index<balloons.size();index++){//go through every balloon
if(balloons.get(index).theName.equals(balloonName){//if this is the ballon you are looking for
balloons.remove(index);//remove it
return true;//line z
}
}
return false;
}
This method will look for the Balloon specified by name and remove the first instance of it, returning true if it actually found and removed the balloon, otherwise removing it. If you wish to remove all balloons by that name, you can create a boolean b at the beginning of the method and set it to false. Then, you can change line z to
b=true;
and then at the bottom of the method, return b.
Now, by edit, you could mean one of two things. If you're planning on modifying the actual name of the balloon, you can use a loop like the one I made above and just modify the name when you find it, again you can make it modify all balloons with that name, or just the first one you find.
Or, if by modify a balloon you mean to replace the balloon in the ArrayList with a new balloon that has a different name, you will want to use the following methods:
balloons.remove(i);//remove balloon at index
balloons.add(i,newBalloon);//put the new balloon(with different data) at the index of the old one
This question already has answers here:
Assigning variables with dynamic names in Java
(7 answers)
Closed 9 years ago.
I want to create new object and to give it user input name.
Example user input "robert" wil match to:
Action robert = new Action();
robert.eat();
What do I need to change in the program so I can create a new object with a dynamic name?
Many Thanks.
I write the next code:
import java.util.Scanner;
public class Human {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner user_input = new Scanner( System.in );
String first_name;
System.out.print("Enter your first name: ");
first_name = user_input.next( );//robert
System.out.println("You are " + first_name);//robert
Action first_name = new Action();
Food orange = new Food();
robert.eat(orange);
}
}
Java, unlike other languages, does not have a way to dynamically create variable names. Variable names are declared in the code. In order to achieve what you're trying to do, look into the Collection's Map interface. This will allow you to "map" a user given name to some value.
Quick example:
//1) Setup the mapping,
//The first parameter to put() is the key (perhaps a user given name?)
//and the second parameter is actual value you want to map for that key.
//note that although I'm using a String as the key and a String as the value
//You can use pretty much any object as the value. Keys are recommended to be
//immutable objects (a String is a good one)
Map<String,String> mMap = new HashMap<String,String>();
mMap.put("John", "Orange");
mMap.put("Steve","Apple");
//2) Once the map is setup, you can then retrieve values given a key:
System.out.println("John's fruit is: "+mMap.get("John"));
More info here.
This is not possible. How can you declare the name of the Class object as a variable.
Variable names cant be specified(created) at run time(dynamically).
I have a class named AirMain where I took in inputs from the user of airline information. I have another class named Airline where constructors are created to store the user input as as Airline object which then store into ArrayList named "info".
I have another ArrayList named "query" storing objects from Airline class but different parameter from the "info" ArrayList.
When I tried to pass both of these ArrayList to another class method (named earliestDepart() in Airline class), I receive error "Cannot find symbol; location: class Object". It is quite a lengthy code, so please see below for a snapshot of the passing to other method of another class and the point where error happens.
Please advise me how do I pass Arraylist containing of objects to another class for process. Thanks in advance!
Code in AirMain Class
ArrayList <Airline> info = new ArrayList<Airline>();
ArrayList <Airline> query = new ArrayList<Airline>();
Airline createAirline = new Airline (fromCity, toCity, departTime, arriveTime, cost);
info.add(createAirline);
Airline createQuery = new Airline(type, fromCity, toCity);
query.add(createQuery);
if (query.get(i).getType() == 1) { query.get(i).earliestDepart(info); }//end of if type 1
Code in Airline Class
public void earliestDepart(ArrayList info){
String retrieve = info.get(i).getFromCity();//error kicks into this statement
}
You need to modify the info argument in your earliestDepart() method like this:
public void earliestDepart(List<Airline> info){
String retrieve = info.get(i).getFromCity();//error kicks into this statement
}
Pass by value to earliestDepart method.
public void earliestDepart(List<Airline> infoList){...}
Just a really quick question about something small. The following is part of a programming assignment for my programming 2 class. It focuses on inheritance and multiple classes. I've answered the question but want to consolidate the classes into a main function and actually build something rather than just submitting the bare minimum.
My question is the section of code below. The user runs the program, is presented with a dialog asking him as to what he's like to add (a CD or a Movie, they're both separate classes).
What I would like though, is for the user to actually name the specific instance of the class while the program is running. So, the user will click Movie for example, be prompt to enter a name and then next line to use the constructor in the movie class to create a new instance class with the name the user entered? Is this possible? I tried using a simple string x = JOptionpane and then naming the class x also, but it didn't work. I'm thinking there might be some method that will refer to the string? like contents.x maybe?
thanks in advance!
import javax.swing.JOptionPane;
public class Main
{
public static void main (String args [])
{
Object[] options = {"Movie",
"CD",
"Cancel"};
int n = JOptionPane.showOptionDialog(null, "Would you like to add an item?","Product",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[2]);
switch(n)
{
case 0:
String moviet = JOptionPane.showInputDialog("Title:");
int movieID = Integer.parseInt(JOptionPane.showInputDialog("ID:"));
Movie moviett = new Movie(moviet, movieID);
}
}
}
If it's not too far beyond your class' content, you could use a Map<String, Media>1 to store instances identified by a runtime-specified string.
Map<String, Media> instances = new HashMap<>();
// snip...
String moviet = JOptionPane.showInputDialog("Title:");
int movieID = Integer.parseInt(JOptionPane.showInputDialog("ID:"));
Movie moviett = new Movie(moviet, movieID);
instances.put("some user-provided string", moviett);
1Assuming that Movie and CD both extend/implement Media.
Java doesn't work this way, and in fact variable names are much less important than you think and almost don't exist in compiled code. Instead how about using Strings to set a field of the Movie class, perhaps a String field called "name". If you want to retrieve a class instance based on a String, consider using a Map such as a HashMap.