import java.util.Scanner;
class BloodData{
static Scanner in = new Scanner(System.in);
static String bloodType;
static String rhFactor;
public BloodData(){
bloodType = "O";
rhFactor = "+";
}
public BloodData(String bt, String rh){
bloodType = bt;
rhFactor = rh;
}
public void display() {
System.out.println(bloodType+rhFactor+" is added to the blood bank");
}
public static void main(String[]args) {
System.out.println("Enter Blood Type(O, A, B, AB)");
System.out.println("Enter rhFactor('+' or '-')");
BloodData bd= new
BloodData(BloodData.bloodType=in.nextLine(),BloodData.rhFactor=in.nextLine());
BloodData bd1= new BloodData();
bd.display();
}
}
How can i use the constructor with 2 String parameters? because when I always run the code the first one only run. I'm only a beginner so hope someone could help because I already watched a lot of Youtube vids and I really didn't know why this happens
Java doesn't use named parameters like this for method or constructors. I would be surprised if a video showed such syntax...
new BloodData(BloodData.bloodType=in.nextLine(),BloodData.rhFactor=in.nextLine())
You need to define String variables on the line above, then pass them into the constructor. You also shouldn't be combining instance constructors with static variables
class BloodData{
private String bloodType;
private String rhFactor;
public BloodData(String type, String rhFactor) {
this.bloodType = type;
this.rhFactor = rhFactor;
}
...
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String x = in.nextLine();
String y = in.nextLine();
BloodData bd = new BloodData(x, y);
}
if you want to call a constructor having two parameters: Use this
BloodData blooddata = new BloodData("A","+");
Related
I have already created an object and tried to set some variables but I cannot find the type of the variables that should I create in order to do not have any problem.
The part of the main class:
Menu menu = new Menu();
scanner.nextLine();
System.out.println("Give a code.");
String code = scanner.nextLine();
menu.setCode(code);
System.out.println("Give a main dish");
String MainDish = scanner.nextLine();
menu.setMainDishes(MainDish);
System.out.println("Give a drink.");
String Drink = scanner.nextLine();
menu.setDrinks(Drink);
System.out.println("Give a sweet.");
String Sweet = scanner.nextLine();
menu.setSweets(Sweet);
And the Menu class:
public class Menu {
ArrayList<String> MainDishes = new ArrayList<>();
ArrayList<String> Drinks = new ArrayList<>();
ArrayList<String> Sweets = new ArrayList<>();
private String code;
public ArrayList<String> getMainDishes() {
return MainDishes;
}
public void setMainDishes(ArrayList<String> mainDishes) {
MainDishes = mainDishes;
}
public ArrayList<String> getDrinks() {
return Drinks;
}
public void setDrinks(ArrayList<String> drinks) {
Drinks = drinks;
}
public ArrayList<String> getSweets() {
return Sweets;
}
public void setSweets(ArrayList<String> sweets) {
Sweets = sweets;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
Compliler give an error because of the String variables that I created.
Your menu class contains ArrayList variables and you try to assign a String to them. Instead of:
menu.setMainDishes(MainDish);
Try:
menu.getMainDishes().add(MainDish);
Also, common convention in Java is to start variables with lowercase, eg mainDish.
You are trying to pass a string when the methods are expecting an ArrayList of strings. If you want to do it the way you currently are, then create an ArrayList, put the user input into it, then pass that ArrayList to the methods that call for it.
This question already has answers here:
Instantiating inner class
(3 answers)
Closed 4 years ago.
I have already make a class "CdFilm" in different file with main class. But I can't instantiate the new object with my own class. I instantiate it like this :
FileRentalVCD.CdFilm film = new FileRentalVCD.CdFilm(1);
This is the class "CdFilm" file :
public class FileRentalVCD {
private String judul, publisher;
private char kategori;
private int stok;
public class CdFilm {
//inheritance from FileRentalVCD
private String judul, publisher;
private char kategori;
private int stok;
//atribut class CDFilm
private String pemain, sutrdara;
//constructor
public CdFilm (int s) {
this.stok = s;
}
//methods encapsulation
public String getJudul() {
return judul;
}
public void setJudul(String judul) {
this.judul = judul;
}
}
}
And this is the main class, where i instantiate my object :
public class RentalVCD {
public void EntriCdFilm (FileRentalVCD.CdFilm input) {
Scanner scan = new Scanner(System.in);
System.out.println("Masukan Judul : ");
String judul = scan.next();
input.setJudul(judul);
}
public static void main(String[] args) {
System.out.println("Rental VCD Alif");
System.out.println("1. Entri data CdFilm");
System.out.println("2. Entri data CdMusik");
System.out.println("3. Tampilkan data CdFilm");
System.out.println("4. Tampilkan data CdMusik");
Scanner scan = new Scanner(System.in);
int pilihan = scan.nextInt();
FileRentalVCD.CdFilm film = new FileRentalVCD.CdFilm(1);
}
}
You can, just not with that syntax. It's somewhat counter-intuitive, but you can use the following to create an instance of your inner class:
FileRentalVCD.CdFilm film = new FileRentalVCD(/* add any args here */).new CdFilm(1);
This is needed because you need an instance of your outer class to create an instance of the inner class.
I have the object numberlist that i created in create() method and i want to access it so i can use it in the question() method.
Is there another way to do this that I probably missed? Am I messing something up? If not, how should I do this to get the same functionality as below?
private static void create() {
Scanner input = new Scanner(System.in);
int length,offset;
System.out.print("Input the size of the numbers : ");
length = input.nextInt();
System.out.print("Input the Offset : ");
offset = input.nextInt();
NumberList numberlist= new NumberList(length, offset);
}
private static void question(){
Scanner input = new Scanner(System.in);
System.out.print("Please enter a command or type ?: ");
String c = input.nextLine();
if (c.equals("a")){
create();
}else if(c.equals("b")){
numberlist.flip(); \\ error
}else if(c.equals("c")){
numberlist.shuffle(); \\ error
}else if(c.equals("d")){
numberlist.printInfo(); \\ error
}
}
While interesting, both of the answers listed ignored that fact that the questioner is using static methods. Thus, any class or member variable will not be accessible to the method unless they are also declared static, or referenced statically.
This example:
public class MyClass {
public static String xThing;
private static void makeThing() {
String thing = "thing";
xThing = thing;
System.out.println(thing);
}
private static void makeOtherThing() {
String otherThing = "otherThing";
System.out.println(otherThing);
System.out.println(xThing);
}
public static void main(String args[]) {
makeThing();
makeOtherThing();
}
}
Will work, however, it would be better if it was more like this...
public class MyClass {
private String xThing;
public void makeThing() {
String thing = "thing";
xThing = thing;
System.out.println(thing);
}
public void makeOtherThing() {
String otherThing = "otherThing";
System.out.println(otherThing);
System.out.println(xThing);
}
public static void main(String args[]) {
MyClass myObject = new MyClass();
myObject.makeThing();
myObject.makeOtherThing();
}
}
You would have to make it a class variable. Instead of defining and initializing it in the create() function, define it in the class and initialize it in the create() function.
public class SomeClass {
NumberList numberlist; // Definition
....
Then in your create() function just say:
numberlist= new NumberList(length, offset); // Initialization
Declare numberList outside your methods like this:
NumberList numberList;
Then inside create() use this to initialise it:
numberList = new NumberList(length, offset);
This means you can access it from any methods in this class.
class states{
List<String> cities = new ArrayList<String>();
public void add_city(String current_city){
this.cities.add(current_city);
}
}
class add_values{
public static void main(String [] args){
System.out.println("Enter the state name : ");
Scanner sc = new Scanner(System.in);
String user_state = sc.nextLine(); // need to create an object with the name from a string value
states user_state = new states();
....
....
}
}
Is there a way to create an object for a class with the name from a string.
If, user enters the state name as "Michigan", an object is created with "Michigan" which is got from scanner. and cities can be added for the state Michigan.
You will want to understand that objects have no names -- none, zero, zip. Yes, variables can have names, but that is not the same, since two or more variables can refer to the same object, and when that happens, which name is the name for the object? Again, neither/none since objects don't have names. As for variable names, they're way less important than you believe and almost don't exist in compiled code. What is most important are object references. Here an object can be associated with a String by means of a Map such as a HashMap<String, String> which is similar to an array or ArrayList that uses a String as its index rather than a number.
Now having said this, you can give your State class a String name field, and this may serve your purposes well.
i.e.,
import java.util.ArrayList;
import java.util.List;
public class State {
private String name;
private List<String> cities = new ArrayList<>();
public State(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void addCity(String city) {
cities.add(city);
}
public List<String> getCities() {
return cities;
}
#Override
public String toString() {
return "State of " + name + ", Cities: " + cities;
}
}
Which can be run like:
public class StateTest {
public static void main(String[] args) {
State illinois = new State("Illinois");
illinois.addCity("Chicago");
illinois.addCity("Peoria");
illinois.addCity("Springfield");
System.out.println(illinois);
}
}
You can do something different using HashMap. Hope this will help to achieve your goal. Here is the code:
class States{
List<String> cities = new ArrayList<String>();
public void add_city(String current_city){
this.cities.add(current_city);
}
}
class add_values{
public static void main(String [] args){
HashMap<String, States> userStatesMap = new HashMap<String, States>();
System.out.println("Enter the state name : ");
Scanner sc = new Scanner(System.in);
String user_state = sc.nextLine(); // need to create an object with the name from a string value
userStatesMap.put(user_state, new states());
....
....
}
}
I can access the planetName, but not the Surfacematerial,Diameter etc because they are not in the array and in the object. How do I access the objects in a loop and their respective fields?
import java.util.Scanner;
public class Planet {
private String[] planetName;
private String SurfaceMaterial;
private double daysToOrbit;
private double diameter;
public Planet(){
planetName=new String[8];
SurfaceMaterial="";
daysToOrbit=0;
diameter=0;
}
public Planet(String[] planetName, String SurfaceMaterial,double daysToOrbit, double diameter){
this.planetName=planetName;
this.SurfaceMaterial=SurfaceMaterial;
this.daysToOrbit=daysToOrbit;
this.diameter=diameter;
}
public void setPlanetName(){
Scanner in=new Scanner(System.in);
Planet solar[]=new Planet[8];
for(int i=0;i<solar.length;i++){
solar[i]=new Planet(planetName,SurfaceMaterial,daysToOrbit,diameter);
System.out.println("Enter Planet Name::");
planetName[i]=in.next();
System.out.println("Enter Surface Material");
SurfaceMaterial=in.next();
System.out.println("Enter Days to Orbit");
daysToOrbit=in.nextDouble();
System.out.println("Enter Diameter");
diameter=in.nextDouble();
}
for(int i=0;i<solar.length;i++){
System.out.println(planetName[i]);
System.out.println(this.SurfaceMaterial); //This returns only one value that has been entered at the last
}
}
}
public static void main(String[] args) {
Planet planet=new Planet();
Scanner input=new Scanner(System.in);
planet.setPlanetName();
}
}
just access like following
object[index].member ... // or call getter setter
in your case say the first member name is name .. so call like
staff[0].name // this will return BOB
The staff array is declared as local in the Constructor: Or if it is declared in the class context, you are hiding it. So declare the staff array in the class context and then initialize in the constructor:
class Test
{
public Full_time [] Staff;
public Test()
{
Staff = new Full_time [4];
Staff [0] = new Full_time("BoB", 2000, 70000);
Staff [1] = new Full_time("Joe", 1345, 50000);
Staff [2] = new Full_time("Fan", 3000, 80000);
}
}
And then, in the main function:
public static void main(String[] args) {
Tester t = new Tester();
t.staff[i].name = "A Name";
}
However, instead of accessing member field directly it is suggested to use getter or setter function like: getStaff(i) and similar.