Any tips why my code is taking null as output value instead of the parameter passed on. Kindly please guide me through the code.
Parent Class:
class Language{
protected String name;
protected int numSpeakers;
protected String regionsSpoken;
protected String wordOrder;
public Language(String getName, int getNumSpeakers, String getRegionsSpoken, String getWordOrder){
this.name = getName;
this.numSpeakers = getNumSpeakers;
this.regionsSpoken = getRegionsSpoken;
this.wordOrder = getWordOrder;
}
public void getInfo(){
System.out.println(name+ " is spoken by "+numSpeakers+" people mainly in "+regionsSpoken);
System.out.println("The language follows the word order: "+wordOrder);
}
public static void main(String[] args){
Mayan mayanLanguage = new Mayan("Ki'che'",30000);
mayanLanguage.getInfo();
}
}
Child Class:
class Mayan extends Language {
protected String name;
protected int numSpeakers;
Mayan(String languageName,int speakers ){
super(languageName,speakers,"Central America","verb-object-subject");
}
#Override
public void getInfo() {
System.out.println(name+" is spoken by "+numSpeakers+" people mainly in Central America.");
System.out.println("The language follows the word order: verb-object-subject");
System.out.println("Fun fact: "+name+" is an ergative language.");
}
}
I have looked into the code and tried to resolve it by making changes but nothing seems to work, i am getting stuck into what is the mistake that i am not seeing in the code.
Expected is:
Ki'che' is spoken by 2330000 people mainly in Central America.
The language follows the word order: verb-object-subject
Fun fact: Ki'che' is an ergative language.
Actual is:
null is spoken by 0 people mainly in Central America.
The language follows the word order: verb-object-subject
Fun fact: null is an ergative language.
In Mayan you have the fields
protected String name;
protected int numSpeakers;
Removing these will fix your issue. The reason this issue is happening is because when you define the two lines above, you are hiding the two fields from Language and you would have to access the fields from Language like super.name, super.numSpeakers, etc...
Something like the following is what you are probably after.
public class Mayan extends Language {
private static final String REGION = "Central America";
private static final String WORD_ORDER = "verb-object-subject";
public Mayan(String languageName, int speakers) {
super(languageName, speakers, REGION, WORD_ORDER);
}
#Override
public void getInfo() {
super.getInfo();
System.out.println("Fun fact: " + name + " is an ergative language.");
}
}
As Gavin pointed out, the access modifiers can be restricted. If you are working within a single package for your program, you might end up with something like
Language.java
class Language {
String name;
private int numSpeakers;
private String regionsSpoken;
private String wordOrder;
Language(String getName, int getNumSpeakers, String getRegionsSpoken, String getWordOrder) {
this.name = getName;
this.numSpeakers = getNumSpeakers;
this.regionsSpoken = getRegionsSpoken;
this.wordOrder = getWordOrder;
}
void getInfo() {
System.out.println(name + " is spoken by " + numSpeakers + " people mainly in " + regionsSpoken);
System.out.println("The language follows the word order: " + wordOrder);
}
public static void main(String[] args) {
Mayan mayanLanguage = new Mayan("Ki'che'",30000);
mayanLanguage.getInfo();
}
}
Mayan.java
class Mayan extends Language {
private static final String REGION = "Central America";
private static final String WORD_ORDER = "verb-object-subject";
Mayan(String languageName, int speakers) {
super(languageName, speakers, REGION, WORD_ORDER);
}
#Override
void getInfo() {
super.getInfo();
System.out.println("Fun fact: " + name + " is an ergative language.");
}
}
Related
Im trying to make a program that allows the client to input a String. The string length should have 3 characters only and should contain the letters .
My program have to pass through this table and check what this string refers to..
Let's say the client passed this String "AUG", my program should show the name of this String which is "Met".
I made a code, and it worked but it has more then 15 if else-if condition.
My question is : Is there any other way to do it without using if else-if (or switch).
And does polymorphism work in this case ?
Have a look at HashMap
You can build your table with:
Map<String, String> table = new HashMap<>();
table.put("AUG", "Met");
table.put(...);
Then access your table using the user's input:
if(table.containsKey(input)){
return table.get(input);
}
I think I'd go about it with an enum personally (provided performance wasn't a significant concern):
public enum Abbreviations {
Ala("GCU", "GCC", "GCA", "GCG"),
Arg("CGU", "CGC", "CGA", "CGG", "AGA", "AGG")
// ...
;
private final List<String> codons;
private Abbreviations(final String... codons) {
this.codons = Arrays.asList(codons);
}
public boolean contains(final String codon) {
return this.codons.contains(codon);
}
}
And then you can find their matching from the String using something like:
public String find(final String codon) {
for (final Abbreviations abb : Abbreviations.values()) {
if (abb.contains(codon)) {
return abb.name();
}
}
throw new IllegalArgumentException("Unknown codon: '" + codon + "'");
}
You could try an Object Oriented Aproach:
//This is your representation of Codon
//Which has a name e.g. Alanine and an Abreviation object.
public class Codon {
private String name;
private Abreviation abreviation;
public Codon(String name, Abreviation abreviation) {
this.name = name;
this.abreviation = abreviation;
this.abreviation.addCodon(this);
}
#Override
public String toString() {
return "Codon [name=" + name + ", abreviation=" + abreviation + "]";
}
}
import java.util.ArrayList;
import java.util.List;
// This is a representation of an abreviation object
// Which has an abreviation: ALA;
// and the name of the abreviation "Alanine".
public class Abreviation {
private String abreviation;
private String name;
private List<Codon> codons = new ArrayList<>();
public Abreviation(String abreviation, String name) {
super();
this.abreviation = abreviation;
this.name = name;
}
public boolean addCodon(Codon codon) {
return this.codons.add(codon);
}
#Override
public String toString() {
return "Abreviation [abreviation=" + abreviation + ", name=" + name + "]";
}
}
// Here is your program, where it's being build all the Codons structure with your respective Abbreviation.
public class App {
public static void main(String[] args) {
// This is abreviation, it'll will associated with the codon
Abreviation alanine = new Abreviation("Ala", "Alanine");
// Here it's being build the codon CGU, which has abreviation alanine
Codon GCU = new Codon("GCU", alanine);
// Then using toString method it prints what have been done
System.out.println(GCU);
}
}
You can put all of your codons into a List, so you can search and retrieve then.
I´m new to programming and I have this task to implement a simple booking System for bus tickets.
We´re supposed to implement a method that adds new bus routes using the attributes: busNumber, start, destination, price, currency. To save the bus routes I´m using an arraylist and save new objects like this:
Booking.add(new Booking(1, "France", "Latvia", 2.05, Currency.EUR))
My issue now is working with those objects since they don´t have a name. I don't know the exact number of objects, so I have to do it this way (i think so at least). Where the issue occurred is at the method "remove", that is supposed to remove a bus route. I thought I could use an Iterator to iterate through the ArrayList and compare the busNumbers but it´s not working.
Another issue I have is, that when I want to print all the objects in my Array list it just prints the last object as many times as there are objects in my ArrayList. Also, my method and attributes are all static now otherwise I wouldn´t know how to use them in another class.
Does anybody has some advice for a newbie please?
My Code is below:
import java.util.ArrayList;
import java.util.Iterator;
public class Booking {
static int busNumber;
static int customerID = 1; //First customerID starts with 1
static String name;
static double price;
static int invoiceNumber = 1; //First invoicenumber starts with 1.
static String start;
static String destination;
static Currency currency;
static ArrayList<Booking> bookable = new ArrayList<Booking>();
//Constructor
public Booking(int busNumber, String start, String destination, double price, Currency currency) {
this.busNumber = busNumber;
this.start = start;
this.destination = destination;
this.price = price;
this.currency = currency;
}
public int getBusNumber() {
return busNumber;
}
public static void add(Booking add) { // add-method. Adds the bus routes to the booking system
bookable.add(add);
}
public static void remove(int busNumber) { // Here´s one of my issues. That´s what i have.
Iterator<Booking> it = bookable.iterator();
if ( == busNumber) {
bookable.remove(it);
}
}
public static void listRoute() {
for (Booking element : bookable) {
Terminal.printLine(toString(element));
}
}
public static String toString(Booking element) {
return "000" + busNumber + " " + start + " " + destination + " " + price + " " + currency;
}
}
My second class which is later supposed to be the UI:
public class Input {
public static void main(String[] args) {
Booking.add(new Booking(1, "Mannheim", "Karlsruhe", 2.05, Currency.EUR));
Booking.add(new Booking(2, "Heidelberg", "Karlsruhe", 3.05, Currency.JPY));
Booking.add(new Booking(3, "Germersheim", "Karlsruhe", 4.05, Currency.USD));
Booking.listRoute();
}
}
The Output is: "0003, "Germersheim", "Karlsruhe", 4.05, Currency.USD" 3 times..
Hi guys,this is my first question on StackOverflow
I am kind of new to java and I need to solve this uml diagram .
I got a solution from one of my classmates but I don't think it's correct and I did it my way. My question is which one of the solutions is correct? I know that the type of relation is an association one . Not an inheritance
Her code
class Sensor {
protected int value;
protected String location;
public Sensor() { // default constructor
value = 0;
location = "North-West";
}
public Sensor(int value, String location) { // overridden constructor
this.value = value;
this.location = location;
}
protected int getValue() { // value getter
return value;
}
protected void setValue(int v) { // value setter
this.value = v;
}
protected void displaySenzorInfo() { // display information on the sensor
System.out.println("Temperature is " + value + ", located " + location + ".");
}
}
class Controller extends Sensor {
protected String name;
public Controller(String name) { // overridden constructor
this.name = name;
}
public Controller(String name, int value, String location) { // overridden
// instructor
this.name = name;
super.value = value;
super.location = location;
}
public Controller() { // default constructor, which creates a new Sensor()
//Sensor s = new Sensor();
}
protected void checkTemperature() { // checks temperature of sensor
System.out.println("Temperature of " + name + " is " + super.value + ", located at " + super.location + ".");
}
}
public class E3 {
public static void main(String[] args) {
Controller control = new Controller();
control.displaySenzorInfo();
Controller c = new Controller("Pizza", 30, "North");
c.checkTemperature();
}
}
My code
class Sensor{
int value;
String location;
Sensor(){
value=0;
location="Sibiu";
}
Sensor(int value,String location){
this.value=value;
this.location=location;
}
int getValue(){
return value;
}
void setValue(int v){
this.value=v;
}
void displaySenzorInfo(){
System.out.println("Temperature is " + value + ", located " + location + ".");
}
}
class Controller{
Sensor tempSensor;
String name;
Controller(){
name="Sibiu";
tempSensor=30;
}
Controller (String name,Sensor tempSensor){
this.name=name;
this.tempSensor=tempSensor;
}
void checkTemperature(Sensor tempSensor){
if (tempSensor>=30)
System.out.println("the temperature is too high!");
else
System.out.println("the temp is too low" );
}
}
public class E3{
public static void main(String []args){
Sensor s1=new Sensor();
Controller c1=new Controller();
c1.displaySenzorInfo();
Controller c2=new Controller(30,"Oliver");
}
}
Please guys. If you have some suggestions or if you see any problems in m program tell me. I know that I will have some errors because I didn't work at this exercise in any IDE because I am at work and I don't have any . Thank you!!!
your solution is the correct one. As you mentioned already, it is an association and not an inheritance. You can see how an inheritance looks like on wikipedia: https://en.wikipedia.org/wiki/Class_diagram
Though overall coding (MyCode) for relationship from the given diagram is OK, I have following observations. (Her code) - Inheritance is not correct. Unidirectional association is correct.
If this is diagram is only for exercise purpose its OK, otherwise it will violate data hiding and encourage client classes to violate encapsulation (Using somebody else's data directly)
tempSensor=30;is not correct for data type.
if (tempSensor>=30) is incorrect for data type and even if you correct, it violates encapsulation (works on somebody else's data) as an effect of first violation of making instance variables non-private. classes should work on their own data.
Even if for some reason we accept above violation, checkTemperature(Sensor tempSensor) makes use of fresh instance of Sensor (for every call), which is not the one obtained from association relationship. This method should not have parameter, it should work on this.tempSensor (with accepted data leakage). Ideally this is indication that data and its behavior are getting separated and design needs to be corrected.
In case the diagram can not be changed then just remove the parameter in checkTemperature() and take care of data types as shown above.
But I would suggest change at Design level as follows for better encapsulation.
public class SensorNew {
private static final double UPPER_THRESHOLD = 25;
private static final double LOWER_THRESHOLD = 20;
private String location;
private Controller controller;
public SensorNew(String location, Controller controller) {
this.location = location;
this.controller = controller;
}
public int getCurrentTemp() {
// obtain from sensor hardware
return 10; // Just example
}
private void makePeriodicCheck(){
double currentTemp = getCurrentTemp();
if (currentTemp > UPPER_THRESHOLD){
controller.coolDown();
} else if (currentTemp < LOWER_THRESHOLD){
controller.heatUp();
} else {
controller.stopIfRunning();
}
}
public void displaySenzorInfo() { // replace by toString()
System.out.println("Temperature is " + getCurrentTemp()
+ ", located " + location + ".");
}
}
public class ControllerNew {
private String name;
// Need to maintain the state of Controller
// either by variable or State design pattern (preferred)
public ControllerNew(String name, Sensor tempSensor) {
this.name = name;
}
public void coolDown() {
// action depending upon current state of controller
}
public void heatUp() {
// action depending upon current state of controller
}
public void stopIfRunning() {
// action depending upon current state of controller
}
}
The advantage is that we do not have to provide public getXX() setXX() methods to these classes. Hence it maintains encapsulation.
I am reletively new to java and have been set some tasks to complete, I (think) I have completed the first two tasks which request I:
Design a class Manual with the following properties:
serial number - string, - default:??????
title - string, - default: Untitled
author - string, - default: Unknown
Write a constructor and a method to print details of a Manual on the console.
.
Amend your Manual class by writing the following additional methods:
methods to set and get the properties of a Manual
a method to ask the user for details of a Manual
a toString() method.
Write a simple application to test your additional methods.
"
So far, I have this code:
public class Manual {
String serialNumber, title, author;
public static void main(String [] args){
Manual man= new Manual();
man.print();
}
public Manual(){
set("??????", "Untitled", "Unknown");
}
public Manual(String serialNumber, String title, String author)
{
set(serialNumber, title, author);
}
public void set(String serialNumber, String title, String author)
{
this. serialNumber = serialNumber;
this. title = title;
this.author = author;
}
public void print()
{
System.out.println("Serial Number : " +serialNumber);
System.out.println("Title : " +title);
System.out.println("Author : " +author);
}
public void print(String heading)
{
System.out.println(heading);
print();
}
public void ask()
{
serialNumber = Console.askString("Please enter the serial number: ");
title = Console.askString("Please enter the title: ");
author = Console.askString("Please enter the author: ");
set(serialNumber, title, author);
}
public String toString()
{
return serialNumber +" " +title +" " +author +" ";
}
}
Would anyone kindly be able to inform me if I have completed all areas of the first two questions correctly, and if there are any mistakes present in my code?
Thank you
The only major issue I see is that you have not implemented the Getters and Setters as was probably intended. In Java most classes have Getters/Setters for each variable that needs to be accessed, something like:
public String getTitle()
{
return title;
}
public void setTitle(String _title)
{
this.title = _title;
}
Also, there is nothing "wrong" with the way you have done the Print and toString functions, but I would have written up the toString to output more similar to how you have print doing it, and then calling toString from the print. Something like:
public String toString()
{
return "SerialNumber: " + serialNumber +"\n"
+"Title: " + title + "\n"
+"Author: " + author +"\n";
}
public void print()
{
System.out.println(this.toString());
}
As a final note, you did not include any code to use this class, as mentioned in the last line of question 2. Hope this helps
This is how I would implement the get() method for all three variables.
public String getSerialNumber(){
return serialNumber;
}
public String getTitle(){
return title;
}
public String getAuthor(){
return author;
}
I am a beginner programmer and this is my first question on this forum.
I am writing a simple text adventure game using BlueJ as a compiler, and I am on a Mac. The problem I ran into is that I would like to make my code more self automated, but I cannot call a class with a string. The reason I want call the class and not have it all in an if function is so that I may incorporate more methods.
Here is how it will run currently:
public class textadventure {
public method(String room){
if(room==street){street.enterRoom();}
}
}
public class street{
public enterRoom(){
//do stuff and call other methods
}
}
The if statement tests for every class/room I create. What I would like the code to do is automatically make the string room into a class name that can be called. So it may act like so:
Public method(string room){
Class Room = room;
Room.enterRoom();
}
I have already looked into using Class.forName, but all the examples were too general for me to understand how to use the function. Any help would be greatly appreciated, and if there is any other necessary information (such as more example code) I am happy to provide it.
-Sebastien
Here is the full code:
import java.awt.*;
import javax.swing.*;
public class Player extends JApplet{
public String textOnScreen;
public void start(){
room("street1");
}
public void room(String room){
if(room=="street1"){
textOnScreen=street1.enterRoom();
repaint();
}
if(room=="street2"){
textOnScreen=street2.enterRoom();
repaint();
}
}
public void paint(Graphics g){
g.drawString(textOnScreen,5,15);
}
}
public abstract class street1
{
private static String textToScreen;
public static String enterRoom(){
textToScreen = "You are on a street running from North to South.";
return textToScreen;
}
}
public abstract class street2
{
private static String textToScreen;
public static String enterRoom(){
textToScreen = "You are on another street.";
return textToScreen;
}
}
Seeing as you are rather new to programming, I would recommend starting with some programs that are simpler than a full-fledged adventure game. You still haven't fully grasped some of the fundamentals of the Java syntax. Take, for example, the HelloWorld program:
public class HelloWorld {
public static void main(String[] args) {
String output = "Hello World!"
System.out.println(output);
}
}
Notice that public is lowercased. Public with a capital P is not the same as public.
Also notice that the String class has a capital S.* Again, capitalization matters, so string is not the same as String.
In addition, note that I didn't have to use String string = new String("string"). You can use String string = "string". This syntax runs faster and is easier to read.
When testing for string equality, you need to use String.equals instead of ==. This is because a == b checks for object equality (i.e. a and b occupy the same spot in memory) and stringOne.equals(stringTwo) checks to see if stringOne has the same characters in the same order as stringTwo regardless of where they are in memory.
Now, as for your question, I would recommend using either an Enum or a Map to keep track of which object to use.
For example:
public class Tester {
public enum Location {
ROOM_A("Room A", "You are going into Room A"),
ROOM_B("Room B", "You are going into Room B"),
OUTSIDE("Outside", "You are going outside");
private final String name;
private final String actionText;
private Location(String name, String actionText) {
this.name = name;
this.actionText = actionText;
}
public String getActionText() {
return this.actionText;
}
public String getName() {
return this.name;
}
public static Location findByName(String name) {
name = name.toUpperCase().replaceAll("\\s+", "_");
try {
return Enum.valueOf(Location.class, name);
} catch (IllegalArgumentException e) {
return null;
}
}
}
private Location currentLocation;
public void changeLocation(String locationName) {
Location location = Location.findByName(locationName);
if (location == null) {
System.out.println("Unknown room: " + locationName);
} else if (currentLocation != null && currentLocation.equals(location)) {
System.out.println("Already in room " + location.getName());
} else {
System.out.println(location.getActionText());
currentLocation = location;
}
}
public static void main(String[] args) {
Tester tester = new Tester();
tester.changeLocation("room a");
tester.changeLocation("room b");
tester.changeLocation("room c");
tester.changeLocation("room b");
tester.changeLocation("outside");
}
}
*This is the standard way of formating Java code. Class names are PascalCased while variable names are camelCased.
String className=getClassName();//Get class name from user here
String fnName=getMethodName();//Get function name from user here
Class params[] = {};
Object paramsObj[] = {};
Class thisClass = Class.forName(className);// get the Class
Object inst = thisClass.newInstance();// get an instance
// get the method
Method fn = thisClass.getDeclaredMethod(fnName, params);
// call the method
fn.invoke(inst, paramsObj);
The comments below your question are true - your code is very rough.
Anyway, if you have a method like
public void doSomething(String str) {
if (str.equals("whatever")) {
// do something
}
}
Then call it like
doSomething("whatever");
In Java, many classes have attributes, and you can and will often have multiple instances from the same class.
How would you identify which is which by name?
For example
class Room {
List<Monster> monsters = new ArrayList <Monster> ();
public Room (int monstercount) {
for (int i = 0; i < monstercount; ++i)
monsters.add (new Monster ());
}
// ...
}
Monsters can have attributes, and if one of them is dead, you can identify it more easily if you don't handle everything in Strings.