I recently had an interview,they asked me a small question
the question is follows
There is list of Students
List<Student> students;
Class Student{
String rollNo;
Map<String, Integer> marks ;
}
Stdunt.marks is actually cobination of subject and mark
Should write an method which should return top 10 students array according to the subject.
List<Student> getTop10(String subjectName){
}
The answer i have given is blelow
private static void PrintTop5(ArrayList<Student> list,String subject){
Collections.sort(list, new Comparator<Student>() {
#Override
public int compare(Student st1, Student st2) {
// TODO Auto-generated method stub
return st2.getSubjectMark(subject) - st1.getSubjectMark(subject);
}
});
ArrayList<Student> studentList = new ArrayList<Student>(list.subList(0,5));
for(Student student : studentList){
System.out.println(student.getRollNum() + " MARK : "+student.getSubjectMark(subject));
}
}
Student class look like below
package com.main;
import java.util.HashMap;
public class Student {
private String rollNo;
private HashMap<String, Integer> marks ;
public Student(){
marks = new HashMap<>();
}
public void setRollNumber(String number){
this.rollNo = number;
}
public void setSubjectAndMark(String subName,int mark){
this.marks.put(subName, mark);
}
public HashMap<String, Integer> getAllMarks(){
return marks;
}
public int getSubjectMark(String subject){
return marks.get(subject);
}
public String getRollNum(){
return rollNo;
}
}
In general your idea is correct, to sort the entire list and take top N students, in fact with java 8 it would look cleaner.
private static void PrintTop5(ArrayList<Student> list,String subject){
list.sort(Comparator
.comparing((Student student) -> student.getSubjectMark(subject))
.reversed());
List<Student> studentList = list.stream().limit(5).collect(Collectors.toList());
for(Student student : studentList){
System.out.println(student.getRollNum() + " MARK : "+student.getSubjectMark(subject));
}
}
Related
Im trying to access the Spring splitting method from Person class in Main class, but it doesn't show me only the last result from the text. Its working very good when im integrating System.out.prinln in Person class, in method body but In this homework im not aloud to use System.out in Person class, only in Main class. The result must split the text in "Surname , Name , City". Where am i doing wrong? Thank you!
public class Person {
public String surname;
public String name;
public String city;
public Person(String text) {
String[] person = text.split(" ");
for (int i = 0; i < person.length; i++) {
String surname = person[i].split("[.]")[0];
String name = person[i].split("[./]")[1];
String city = person[i].split("/")[1];
this.surname = surname;
this.name = name;
this.city = city;
}
}
}
public class Main {
public static void main(String[] args) {
Person p1 = new Person("John.Davidson/Berlin Michael.Barton/Rome Ivan.Perkinson/Munich");
System.out.println(p1.surname + p1.name + p1.city);
// the result is the only the last persons info
}
}
I am trying to display a value from an Array of classes as follows:
class Person
{
private int age;
private string name;
public Person(string Name, int Age)
{
this.name = Name;
this.age = Age;
}
}
class Program
{
static void Main(string[] args)
{
Console.Write("No. of family members: ");
int NoOfEntities = Convert.ToInt32(Console.ReadLine());
Person[] people = new Person[NoOfEntities];
for (int person = 0; person < people.Length; person++)
{
Console.Write($"\nName of No. {person + 1} member: ");
string Name = Console.ReadLine();
Console.Write($"\nAge of No. {person + 1} member: ");
int Age = Convert.ToInt32(Console.ReadLine());
people[person] = new Person(Name, Age);
}
Console.WriteLine(people[0].Age);
}
}
but the compiler complains that 'Person' does not contain a definition for 'Age'. All of the examples I found on internet are using the same method to iterate over the array members. What am I doing wrong?
In your 'Person' class, you have defined age and name as private fields, so they are not accessible from outside of the class (that is why you getting the compiler error). Also note that C# is case sensitive, so age is not the same as Age.
In C# it is common to use public properties for data. It is also common to use names that start with lower case letters for function parameters and local variables. So you probably want your Person class to look like this:
class Person
{
public int Age { get; set; }
public string Name { get; set; }
public Person(string name, int age)
{
this.Name = name;
this.Age = age;
}
}
//Is there a better way of displaying the returned information, without having to write the everything I wrote in the S.O.P. The goal is to return the value then link it to the name and time of the racer. Thanks for your help.//
public class array_Test
{
public static void main(String args[])
{
String[] names={"Bob", "Tj", "Aj"};
double [] times={9.9,9.8,10.0};
double x=findLargest(times);
System.out.print("The slowest racer was " + names[1] + " with a time of "
+ times[1] + " at index position" + x);
}
public static double findLargest(double[] times)
{
int indexOfLargest=0;
double largest=times[0];
for(int i=0; i<times.length; i++)
{
if(times[i]>largest)
{
largest=times[i];
indexOfLargest=i;
}
}
return indexOfLargest;
}}
Why don't use class ? You can merge the names and the times of the racers with something like that :
public class Racer {
private String name;
private double time;
private int position;
public Person(String name, double time){
this.name = name;
this.time = time;
this.position =-1;
}
public String getName() {
return name;
}
public double getTime() {
return time;
}
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position
}
#Override
public String toString() {
return "The slowest racer was " + getName + " with a time of "
+ getTime + " at index position" + getPosition);
}
}
This class allow you to manage easlier your "Racer" and the override of the function toString() allow you to customize your printl().
You can now change your code with this :
public class array_Test
{
public static void main(String args[])
{
Racer[] people ={new Person("Bob",9.9),new Person("Tj",9.8),new Person("Aj",10.0)};
double x=findLargest(times);
System.out.print(Racer[x].toString());
}
public static double findLargest(double[] times)
{
int indexOfLargest=0;
double largest=people[0].getTime();
for(int i=0; i<people.length; i++)
{
if(people[i].getTime()>largest)
{
largest=people[i].getTime();
indexOfLargest=i;
}
}
people[indexOfLargest].setPosition(indexOfLargest);
return indexOfLargest;
}}
Consider below example:
public class sample{
private Map myMap;
public Map getMap(){
return myMap;
}
}
In above example, we are returning the map to some other calling class. So my question is how we can say that this class encapsulates/protects its data. The Map that will be returned will be available for modification by other classes.
Thanks,
Rajan
Consider this class Person, which have 2 attributes (name and age).
package app;
/**
*
* #author salathielgenese
*/
public final class Person
{
public Person()
{
setAge(age);
setName(name);
}
public Person(String name, long age)
{
setName(name);
setAge(age);
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public long getAge()
{
return age;
}
public void setAge(long age)
{
this.age = age;
}
private String name;
private long age;
}
Now imagine that some one (let say the calling class) set the age to -19. This will generate inconsistency in your that.
So when you protect your data, your controlling wich kind of action are made possible these data.
You may decide that if the given age is lower than 0 then the age will be set to 0 for example. The code may become...
public void setAge(long age)
{
this.age = age;
if (age < 0)
{
this.age = 0;
}
}
You can do the same with name attribute to prevent setting it to null.
public void setName(String name)
{
this.name = name;
if (name == null || name == "")
{
this.name = "NO NAME";
}
}
We'll say that encapsulation help protecting data.
··························································································
Now let's imagine a class called Carpenter. When you need a table, you just ask it to him. Thus the Carpenter class should provide a method which takes a description of the table you need, and return the build table. Assuming that the method is called buildTable, this method will be declared with public access because it's useful to call it from another Class.
When you ask to the Carpenter to build up your Table, he will need to check some material as well as saw, needle and so on and so far. We (calling class) don't care about this internal mechanism and all methods as well as attributes involved in this process will be declared with private access. i.e to prevents external classes from modifying them, i.e to encapsulate our fields and methods for better protection.
Encapsulating a field let us control access to our data.
Comming back to your code, giving public access to getMap() doesn't prevent calling class to modify its content.
Now look at this Example
Person.java
package app;
/**
*
* #author salathielgenese
*/
public final class Person
{
public Person()
{
setAge(age);
setName(name);
}
public Person(String name, long age)
{
setName(name);
setAge(age);
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
if (name == null || name == "")
{
this.name = "NO NAME";
}
}
public long getAge()
{
return age;
}
public void setAge(long age)
{
this.age = age;
if (age < 0)
{
this.age = 0;
}
}
#Override
public String toString()
{
return "Person{" + "name=" + name + ", age=" + age + '}';
}
private String name;
private long age;
}
Example.java
package app;
/**
*
* #author salathielgenese
*/
public class Example
{
public Example()
{
}
public Example(Person person)
{
this.person = person;
}
public Person getPerson()
{
return person;
}
public void setPerson(Person person)
{
this.person = person;
}
private Person person;
}
**Main class (Loader.java)
package app;
/**
*
* #author salathielgenese
*/
public class Loader
{
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
// Instantiate an Example with a new created Person
Example example = new Example(new Person("Rajan", 19));
// Retrive person in example and print its description (printing result of implicit call to person.toString() )
Person person = example.getPerson();
System.out.println(person);
// Assigning a new reference to the variable **person** and print its description
person = new Person("Salathiel", 20);
System.out.println(person);
// Print description of Person containning in Example instance
System.out.println(example.getPerson());
}
}
If you look closed this code, you'll understand that you can change attribute of your Map but not the reference to it.
Maybe you can use an unmodifiable map from Java Collection API's :
public class sample{
private Map myMap;
public Map getMap(){
return Collections.unmodifiableMap(myMap));
}
}
I am getting problems with these 2 lines. I need to create a class with an array of Animals using constants to size it. I have to fill the array Animal with Fish and Iterate in 2 different ways through the array executing move() and makeSound().
These are the lines:
1 animals[0] = new Fish()
2 for (Animal animal : animals) {
public class Animals {
public static void main(String[] args) {
final int SIZE = 6;
Animal animal[] = new Animal[SIZE];
animals[0] = new Fish() // 1
for (Animal animal : animals) { // 2
System.out.println("Bubbles");
System.out.println("Swim");
}
}
}
My interface Animal:
public interface Animal {
public void move();
public void makeSound();
}
And my class Fish that implements Animal
public class Fish implements Animal{
#Override
public void move() {
System.out.println("Swim");
}
#Override
public void makeSound() {
System.out.println("Bubbles");
}
private String color;
public String getColor(){
return color;
}
public void setColor(String color){
this.color = color;
//Prefix this.color;
}
}
A couple of syntax errors to fix:
Add a semicolon to the end of animals[0] = new Fish();
Change Animal animal[] = new Animal[SIZE]; to Animal[] animals = new Animal[SIZE];
Also, you should really be doing this in the for loop:
for(Animal animal : animals){
animal.makeSound();
animal.move();
}
Just hard-coding print statements defeats the purpose of having the Animal interface, even if Fish is the only class implementing Animal at the moment.