This question already has answers here:
How to convert an Array to a Set in Java
(19 answers)
Closed 2 years ago.
In my task I already put some cities in array but I now face a problem.
In main i did this:
City[] cities = enterCity(scanner);
In method enter city I had array of 3. So I needed to return name of a city and number of citizens.
In for loop I enter name and number of citizens. At the end of loop I did this:
cities[i]=new City(name, numbersOfCitizens);
and then returned it with City[] cities.
Now I need to improve my code with set.
In method I implemented:
Set<City> cities = new Hashset<>();
I failed to create method add. I tried with this to call it in main:
add.(City(name, numbersOfCitizens));
in City class and return City[] cities says inconvertible types ( so it cannot return anything). Is the right thing to call method like I do in main and if it is how to properly return all values. In class City I have usual get and set method.
Create Set
// Create new Set
Set<City> cities = new HashSet<City>();
// Add new City
cities.add(new City());
Convert Set in to array - option #1
City[] objects = cities.toArray(new City[0]);
Convert Set in to array - option #2
Manual copy:
City[] objects = new City[cities.size()];
int position = 0;
for (City city : cities) {
objects[position] = city;
position++;
}
Working example
public class SetExample {
private static Scanner scanner;
public static void main(String[] args) {
scanner = new Scanner(System.in);
Set<City> cities = readCities();
}
private static Set<City> readCities() {
Set<City> cities = new HashSet<City>();
int numberOfCities = 3;
for (int i = 0; i < numberOfCities; i++) {
City newCity = readCity();
cities.add(newCity);
}
return cities;
}
private static City readCity() {
System.out.print("Name: ");
String name = scanner.nextLine();
System.out.print("Numbers of citizens: ");
int numbersOfCitizens = scanner.nextInt();
return new City(name, numbersOfCitizens);
}
}
Printing
Example of the class:
class City {
private String name;
private int numbersOfCitizens;
public City(String name, int numbersOfCitizens) {
this.name = name;
this.numbersOfCitizens = numbersOfCitizens;
}
}
When you will use without adding toString() method so:
City city = new City("New York", 1234);
System.out.println(city);
you can expect output:
City#19469ea2
To print custom message, you have to override toString() method, for example generate "default" method in IntelliJ:
#Override
public String toString() {
return "City{" +
"name='" + name + '\'' +
", numbersOfCitizens=" + numbersOfCitizens +
'}';
}
or something simple like:
#Override
public String toString() {
return name + " " + numbersOfCitizens;
}
This question already has answers here:
The connection between 'System.out.println()' and 'toString()' in Java
(3 answers)
Closed 2 years ago.
consider the two classes below, why when I call the print method in the second class i get "blueblueblue is blue repeated" instead of "blueblueblue" despite the fact that tostring() was never called
public class Simple{
private String word;
private String phrase;
public Simple(int number, String w) {
word = w;
phrase = mystery(number, w);
}
private String mystery(int num, String s) {
String answer = "";
for (int k=0; k<num; k++) {
answer = answer + s;
}
return answer;
}
public String toString() {
return phrase + " is " + word + " repeated";
}
}
public class TestSimple{
public void print() {
Simple item = new Simple(3, "blue");
System.out.println(item);
}
}
yeah,the system out finally will invoke the
object's toString method. you can get the source code.
This question already has answers here:
how to print the index number of elements in the ArrayList using for each looping
(4 answers)
Closed 4 years ago.
This is my code
ArrayList<Restaurant> restaurant= new ArrayList<Restaurant>();
Inside Restaurant class,
#Override
public String toString() {
int i=1;
return "\n"+(i++)+". "+this.restaurantName +
"\t\t"+this.location;
}
I want to print like this
[ 1. pizzahut bangalore, 2. dominos delhi]
instead it prints
[ 1. pizzahut bangalore, 1. dominos delhi]
Help in code needed.
Here is another solution, I am not sure what actual problem you have, so just provide another possible solution. this might work for you.
public class Restaurant {
static int index = 1;
String restaurantName;
String location;
int curIndex;
Restaurant(final String restaurantName, final String location) {
this.restaurantName = restaurantName;
this.location = location;
this.curIndex = index++;
}
public static void main(final String[] input) {
final ArrayList<Restaurant> restaurant = new ArrayList<Restaurant>();
restaurant.add(new Restaurant("pizzahut", "bangalore"));
restaurant.add(new Restaurant("dominos", "delhi"));
restaurant.forEach(r -> System.out.println(r));
}
public String toString() {
return "\n" + curIndex + ". " + this.restaurantName +
"\t\t" + this.location;
}
}
ArrayList<Restaurant> restaurantList= new ArrayList<Restaurant>();
// your login to insert the elements in the array list
// iterate list
int index=1;
for(Restaurant r : restaurantList){
System.out.println(String.valueOf(index++)+": "+ r);
}
Inside Restaurant class,
#Override
public String toString() {
return this.restaurantName + "\t\t"+this.location;
}
I try to determine the error since yesterday, but did not find him. All I know is where he must be placed approximately. But now to the topic.
For my app I have created a separate class with the name Player. Now if I make an ArrayList with this class, a newly added object overwrites all existing objects. So:
ArrayList empty -> Player is stored in ArrayList
ArrayList already contains a Player -> ArrayList now contains the newest Player instance two times
etc.
Here is my code corresponding to:
Player Object
public Player(String n, int m, int t) {
name = n;
money = m;
tip = t;
}
public String getName() {
return this.name;
}
public int getMoney() {
return this.money;
}
public int getTip() {
return this.tip;
}
public String toString() {
return this.name + "\n Tipp: " + this.tip + " | Einsatz: " + this.getMoney() + " ,- €";
}
Creating the ArrayList
public void addPlayertoEvent(String name, int money, int tip) {
Player p = new Player(name, money, tip);
playerList.add(p);
playerListString.add(p.toString());
lvPlayers.setAdapter(null);
ArrayAdapter<String> playerAdapter = new ArrayAdapter<String>(AddEventActivity.this, R.layout.list_items, playerListString);
lvPlayers.setVisibility(View.VISIBLE);
lvPlayers.setAdapter(playerAdapter);
etTip.setText("");
etName.setText("");
for(int i = 0; i < playerList.size(); ++i) {
Log.e("AL", "" + playerList.get(i).getName() + " " + playerList.get(i).getMoney() + " " + playerList.get(i).getTip());
}
}
Just started taking Java 2, and it has been over 6-7 months since I've taken Java 1 and done much programming at all, so please be kind if I did something dumb
The majority of the three classes below are for a previous assignment where you took a listing from the book and had to add a method called getMax() that returns the value of the highest key in the array, or -1 if the array is empty.
This part worked fine.
For the next part(the part I am having trouble with) we had to modify the assignment so that the item with the highest key is not only returned by the method, but also removed from the array.
To do this I tried:
public long removeMax(PrintWriter pw)
{
long maxIndex;
maxIndex = getMax();
delete(maxIndex);
return maxIndex;
}
But the maxIndex = getMax(); and delete(maxIndex); are giving me errors and I'm not quite sure why. Although I'm convinced I'm just making a small mistake due to being rusty at programming.
The error it is giving me is actual and formal argument lists differ in length. I tried changing and switching things around but no matter what I did nothing seemed to work.
Below are the Employee, HighArrayObject and Project21Rev(class where getMax and removeMax are) classes in full.
public class Employee
{
protected int empNo; // employee number
protected String ssno; // social security number
protected String lastName; // Last name
protected String firstName; // First name
//This constructor initializes the variables
public Employee(int eNo, String ssn, String lName, String fName)
// aliases are used in the function header
{
empNo = eNo; // the alias is assigned to the actual value
ssno = ssn;
lastName = lName;
firstName = fName;
}
// Make a no argument constructor as well
public Employee()
{
empNo = 0;
ssno = "";
lastName = "";
firstName = "";
}
/**
The copy constructor initializes the object
as a copy of another Employee object
#param object2 The object to copy
*/
public Employee(Employee object2)
{
empNo = object2.empNo;
ssno = object2.ssno;
lastName = object2.lastName;
firstName = object2.firstName;
}
// The set method sets a value for each field
public void set(int eNo, String ssn, String lName, String fName)
// aliases are used in the function header
{
empNo = eNo; // the alias is assigned to the actual value
ssno = ssn;
lastName = lName;
firstName = fName;
}
// the getKey method returns the employee number
public int getKey()
{ return empNo; }
// the setKey method sets the employee number
public void setKey(int id)
{ empNo = id; }
// toString method
// returns a string containing the instructor information
public String toString()
{
// Create a string representing the object.
String str = "Employee Number: " + empNo +
"\nSocial Security Number: " + ssno +
"\nLast Name: " + lastName +
"\nFirst Name: " + firstName;
// Return the string;
return str;
}
}
Start of next class
import java.io.*;
class HighArrayObject
{
protected Employee[] emp;
protected int nElems;
public HighArrayObject(int max) // constructor
{
emp = new Employee[max];
nElems = 0;
}
// The createEmployees method creates an Employee object
// for each element of the array
public static void createEmployees(Employee[] emp, int maxsize)
{
int empNo;
String ssno;
String lastName;
String firstName;
// Create the employees
for(int index = 0; index < emp.length; index++)
{
// Get the employee data
emp[index] = new Employee();
}
}
public boolean find(long searchKey, PrintWriter pw)
{
System.out.println("Trying to find item with employee number " + searchKey);
pw.println("Trying to find item with employee number " + searchKey);
int j;
for(j=0; j<nElems; j++)
if(emp[j].empNo == searchKey) // == ok since empNo is a primative
break; // exit loop before end
if(j == nElems) // gone to end?
return false;
else
return true; // no, found it
} // end find()
public void insert(int eNo, String sNo, String lName, String fName, PrintWriter pw)
{
System.out.println("Inserting employee with employee number " + eNo);
pw.println("Inserting employee with employee number " + eNo);
Employee temp = new Employee();
temp.empNo = eNo;
temp.ssno = sNo;
temp.lastName = lName;
temp.firstName = fName;
emp[nElems] = temp;
nElems++;
}
public boolean delete(long value, PrintWriter pw)
{
System.out.println("Deleting employee number " + value);
pw.println("Deleting employee number " + value);
int j;
for(j=0; j < nElems; j++) // look for it
if(value == emp[j].empNo)
break; // can't find it
if(j==nElems)
return false;
else // found it
{
for(int k=j; k<nElems; k++) // move higher ones down
{
emp[k]=emp[k+1];
}
nElems--; // decrement size
return true;
}
} // end delete
public void display(PrintWriter pw)
{
System.out.println("The array of employees is: ");
pw.println("The array of employees is: ");
for(int j=0; j<nElems; j++)
{
System.out.println(emp[j].empNo + " " + emp[j].ssno + " "
+ emp[j].lastName + " " + emp[j].firstName);
pw.println(emp[j].empNo + " " + emp[j].ssno + " "
+ emp[j].lastName + " " + emp[j].firstName);
} // end for
} // end delete
} // end HighArrayObject
Start of next class
import java.io.*;
public class Project21Rev extends HighArrayObject //reference Gaddis p.658
{
public Project21Rev(int max) // subclass constructor
{
super(max); // call superclass constructor
}
public void getMax(PrintWriter pw) // new functionality as required by the assignment
{
int maxIndex = -1; // not found yet
if(nElems == 0)
System.out.println("Number of elements is 0");
else
{
int max = emp[0].empNo; // assume the first value is the largest
maxIndex = 0;
for (int i = 1; i < nElems; i++) //now check the rest of the values for largest
{
if(emp[i].empNo > max)
{
maxIndex = i;
}
}
System.out.println("The largest value is " + emp[maxIndex].empNo + " " + emp[maxIndex].ssno + " " + emp[maxIndex].lastName + " " + emp[maxIndex].firstName);
pw.println("The largest value is " + emp[maxIndex].empNo + " " + emp[maxIndex].ssno + " " + emp[maxIndex].lastName + " " + emp[maxIndex].firstName);
System.out.println("at location " + maxIndex);
pw.println("at location " + maxIndex);
}
}
public long removeMax(PrintWriter pw)
{
long maxIndex;
maxIndex = getMax();
delete(maxIndex);
return maxIndex;
}
// modified find method follows
public void find( int searchKey, PrintWriter pw)
{
System.out.println("Trying to find item with employee number " + searchKey);
pw.println("Trying to find item with employee number " + searchKey);
int j;
Boolean found = false;
for(j=0; j < nElems; j++)
if(emp[j].empNo == searchKey)
{
found = true;
System.out.println("Found " + emp[j].empNo + " " + emp[j].ssno + " " + emp[j].lastName + " " + emp[j].firstName);
pw.println("Found " + emp[j].empNo + " " + emp[j].ssno + " " + emp[j].lastName + " " + emp[j].firstName);
System.out.println("at location " + j);
pw.println("at location " + j);
}
if(found == false)
{
System.out.println(searchKey + " Not found");
pw.println(searchKey + " Not found");
}
}
}
class Project21RevApp
{
public static void main(String[] args) throws IOException
{
// set up printer output file
PrintWriter pw = new PrintWriter(new BufferedWriter
(new FileWriter("output21.dat")));
int maxSize = 100; // array size
Project21Rev arr; // reference to array
arr = new Project21Rev(maxSize); // create the array
arr.insert(77,"A","B","C",pw);
arr.insert(99,"D","E","F",pw);
arr.insert(44,"G","H","I",pw);
arr.insert(55,"J","K","L",pw);
arr.insert(22,"M","N","O",pw);
arr.insert(88,"P","Q","R",pw);
arr.insert(11,"S","T","U",pw);
arr.insert(00,"V","W","X",pw);
arr.insert(66,"Y","Z","AA",pw);
arr.insert(33,"BB","CC","DD",pw);
arr.display(pw); // display items
int searchKey = 35; // search for item
arr.find(searchKey, pw);
searchKey = 22; // search for item
arr.find(searchKey, pw);
arr.delete(00, pw); // delete 3 items
arr.delete(55, pw);
arr.delete(99, pw);
arr.display(pw); // display items again
// new functionality follows
arr.getMax(pw);
pw.close();
} // end main()
} // end class Project21RevApp
Well, the error message actually tells you exactly what's wrong.
Your method delete() accepts two parameters:
public boolean delete(long value, PrintWriter pw) {
// ...
}
You are trying to call it with only one:
delete(maxIndex);
To fix the error, pass the right amount and types of parameters.
Hymm there are too many wrong things. Start by learning what a Method is and how you call it. You are trying to call your method
public void getMax(PrintWriter pw){..}
with
maxIndex = getMax();
Now you see when you deffined that method you told it with VOID that it should return nothing. But it requires a PrintWriter Object. You had the right idea when you created your:
public long removeMax(PrintWriter pw)
you see that method should receive such variable/object and it will be "pw".
So the right way to call your method would be
getMax(pw);
and if you want it to return something you really should just read a bit more about java and the way methods work.
The other big problem is that you are talking about a LIST (abstract data type) but in the code I see
protected Employee[] emp;
Witch is not at all a list but just a simple Array. There is a big difference. If the requirements are that you have an actual java/programming list, then there is no such thing in the Program. It's just an Array that looks like a general list of things, but that is called an Array in most programming languages. Perhaps your teacher makes no difference.
This is not a complete solution but there are too many things to fix and the code is too big for whatever it's suppose to do. Don't get stressed, just continue to read about Java from whatever source you got. Keep in mind you are working with Arrays not a lists in that code and you need to learn some basic information about the language.