how to add multiple object on array list - java

I would like to add multiple objects to an ArrayList but I can't do it with my code. Here is the code I'm currently using. In the for loop, its adding the same object to the ArrayList 5 times. Why is this occurring?
import java.util.ArrayList;
import java.util.Scanner;
public class newBook {
public int no;
public String isim;
public newBook(int no ,String isim){
this.no = no;
this.isim = isim;
}
#Override
public String toString(){
return " no = " + this.no +", name = " + this.isim;
}
public static void main(String args[]){
Scanner klavye = new Scanner(System.in);
int kitapNo = klavye.nextInt();
String kitapName = klavye.next();
ArrayList<newBook> liste = new ArrayList<>();
for(int i=0 ; i<5 ; i++){
liste.add( new newBook(kitapNo,kitapName));
//System.out.println("Çıkmak için -1 giriniz ");
//int i = klavye.nextInt();
}
for (newBook liste1 : liste) {
System.out.println(liste1);
}
}
}

They are not the same object, they just have the same content. You need to read the input from klavye inside the loop too.

Related

Creating a program to read through Integers and Strings in Java

I am trying to create a program that will read from a .txt file that is formatted as such:
Total number of students
Name
Score1
Score2
Score3
Name
Score1
etc
My current code is this:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.io.*;
public class Project5 {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
System.out.println("Enter file name: ");
String filename = in.nextLine();
File filetest = new File(filename);
Scanner imp = new Scanner(filetest);
List<String> studentList = new ArrayList<String>();
List<Integer> studentScores = new ArrayList<Integer>();
String total = imp.nextLine();
int i = 0;
try {
while (imp.hasNext()) {
if (imp.hasNextInt()) {
studentScores.add(imp.nextInt());
} else {
studentList.add(imp.nextLine());
i++;
}
}
} finally {
System.out.println("Name\t\tScore1\t\tScore2\t\tScore3");
System.out.println("-------------------------------------------------------");
System.out.println(total);
System.out.println(studentList.get(0) + "\t" + studentScores.subList(0, 3));
System.out.println(studentList.get(2) + studentScores.subList(3, 6));
System.out.println(studentList.get(4) + studentScores.subList(6, 9));
System.out.println(studentList.get(6) + studentScores.subList(9, 12));
imp.close();
in.close();
}
}
}
The format I want to display into the console is to list the name, then the three scores that student received, and to repeat it, but right now it is hard-coded just for the amount of students that are currently there, and I need it to be able to create output regardless of how many students there are.
Current output:
Total
Name [score1 score2 score3]
etc
Desired output:
Total
Name score1 score2 score3 (rather than with the [] )
etc
Any help is greatly appreciated.
More structural way to do this :
public class Project5 {
static class Student {
private String name;
private final List<Integer> scores;
private int total;
public Student() {
scores = new ArrayList<>();
total = 0;
}
public void setName(String name) {
this.name = name;
}
public void addScore(int score) {
scores.add(score);
total += score;
}
public String getName() {
return name;
}
public List<Integer> getScores() {
return scores;
}
public int getTotal() {
return total;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder(name).append('\t').append(total);
for (Integer score : scores) {
sb.append('\t').append(score);
}
return sb.toString();
}
}
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
System.out.println("Enter file name: ");
String filename = in.nextLine();
in.close();
File filetest = new File(filename);
Scanner imp = new Scanner(filetest);
int total = Integer.parseInt(imp.nextLine());
System.out.println("Name\tTotal\tScore 1\tScore 2\tScore 3");
for (int i = 0; i < total && imp.hasNextLine(); i++) {
Student student = new Student();
student.setName(imp.nextLine());
while (imp.hasNextInt()) {
student.addScore(imp.nextInt());
}
if (imp.hasNext()) {
imp.nextLine();
}
System.out.println(student);
}
imp.close();
}
}
The toString method of a List will return it in that format. If you want a different format, you can do this with a Stream:
System.out.println(studentList.get(2) + studentScores.subList(3, 6).stream().collect(Collectors.joining(" ");
Health warning: if this is for a school assignment where the use of Streams may get you accused of plagiarism, you will need to concatenate the elements yourself the long way.
This is the efficient solution that uses a StringBuilder and no Lists. A StringBuilder is basically a class that helps you to build string. Pretty straightforward.
// 1024 means that the initial capacity of sb is 1024
StringBuilder sb = new StringBuilder(1024);
try {
while (imp.hasNext()) {
if (imp.hasNextInt()) {
// add the scores and "tab" character to the string
sb.append("\t").append(imp.nextInt());
} else {
// add the name to the string
sb.append("\n").append(imp.nextLine());
i++; // btw.. why are you doing this i++ ??
}
}
} finally {
System.out.println("Name\t\tScore1\t\tScore2\t\tScore3");
System.out.println("-------------------------------------------------------");
System.out.println(total);
System.out.println(sb.toString());
imp.close();
in.close();
}
If you do want to use an arraylist then I suggest iterate through the arraylist like an array and print out the scores.

subroutine taking an array as a parameter in Java

In the following program, the user is supposed to enter a String (name of a City) and the program should return the index of the corresponding City in the array.
But I get an error, in the subroutine indexCities the following message:
"nameCity cannot be resolved".
I guess it is a problem of variable scoping but I don't figure out how I should do.
Thanks for your help.
import java.util.Scanner;
public class villes {
public static void main(String[] args) {
String cities[] = {"Vierzon","Salbris","Nouans","LB","LFSA","Orleans"};
Scanner input = new Scanner(System.in);
String nameCity = input.nextLine();
indexCities(cities);
}
public static int indexCities(String cities[]) {
for (int i = 0; i < cities.length; i++) {
if(nameCity.equals(cities[i])) {
System.out.println(i);
break;
}
}
}
}
nameCity is a local variable inside your main method. You can not access it outside the method.
One option for you is to pass the nameCity also as an argument in indexCities method. Also return type of your indexCities method should be void since you are not returning anything.
public static void main(String[] args) {
String cities[] = {"Vierzon","Salbris","Nouans","LB","LFSA","Orleans"};
Scanner input = new Scanner(System.in);
String nameCity = input.nextLine();
indexCities(cities, nameCity);
}
public static void indexCities(String cities[], String nameCity){
for (int i = 0; i < cities.length; i++) {
if(nameCity.equals(cities[i])) {
System.out.println(i);
break;
}
}
}
You could do it in this way:
public static void main(String[] args) {
String cities[] = { "Vierzon", "Salbris", "Nouans", "LB", "LFSA", "Orleans" };
int index = indexCities(cities, "Vierzon");
System.out.println("Index of city Vierzon is: " + index);
}
public static int indexCities(String cities[], String cityName) {
List<String> cityList = Arrays.asList(cities);
return cityList.indexOf(name);
}
Scope of variable nameCity is limited to main function. You can not access it outside of main function.
The variable is out of scope when you try to use it inside the method indexCities. One solution is making the variable nameCity an instance variable by moving it's definition out of the main method, but your code can be improved in several ways too. Check some option below:
This will print the index of the city you're looking for inside the array:
import java.util.Scanner;
public class villes {
public static void main(String[] args) {
String cities[] = {"Vierzon","Salbris","Nouans","LB","LFSA","Orleans"};
Scanner input = new Scanner(System.in);
String nameCity = input.nextLine();
indexCities(nameCity, cities);
}
public static void indexCities(String copyOfNameCity, String cities[]){
for (int i = 0; i < cities.length; i++) {
if(copyOfNameCity.equals(cities[i])) {
System.out.println(i);
break;
}
}
}
}
You you can improve it by making the method return a value. Like this:
import java.util.Scanner;
public class villes {
public static void main(String[] args) {
String cities[] = {"Vierzon","Salbris","Nouans","LB","LFSA","Orleans"};
Scanner input = new Scanner(System.in);
String nameCity = input.nextLine();
int cityIndex = indexCities(nameCity, cities);
System.out.println(cityIndex == -1 ? "City not found" : "City found in index " + cityIndex);
}
public static int indexCities(String nameCity, String cities[]){
for (int i = 0; i < cities.length; i++) {
if(nameCity.equals(cities[i])) {
return i;
}
}
return -1;
}
}
Another way is:
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class test2 {
public static void main(String[] args) {
String cities[] = {"Vierzon", "Salbris", "Nouans", "LB", "LFSA", "Orleans"};
Scanner input = new Scanner(System.in);
System.out.print("Enter the name of city to be searched -> ");
String nameCity = input.nextLine();
int cityIndex = indexCities(nameCity, cities);
System.out.println(cityIndex == -1 ? "City not found" : "Found at position " + cityIndex);
input.close();
}
public static int indexCities(String cityName, String cities[]) {
List<String> cityList = Arrays.asList(cities);
return cityList.indexOf(cityName);
}
}

Java string comparison with object string

So I have an object which I import in another object
First object:
package test;
import java.util.*;
public class Eveniment {
int ziua;
String luna = new String();
public void setZiua(int param){
ziua = param;
}
public void setLuna(String param){
luna = param;
}
public int getZiua(){
return ziua;
}
public String getLuna(){
return luna;
}
}
Second object:
package test;
import test.*;
import java.util.*;
public class EventPlanner {
public static void main(String[] args){
ArrayList<Eveniment> myAr = new ArrayList();
Scanner sc = new Scanner(System.in);
System.out.println("Introduceti ziua urmata de luna evenimentului: ");
int zi = 0;
String luna;
zi = sc.nextInt();
luna = sc.nextLine();
Eveniment first = new Eveniment();
first.setZiua(zi);
first.setLuna(luna);
myAr.add(first);
while(luna!=null && zi!=0)
{
zi = sc.nextInt();
luna = sc.nextLine();
if(zi!=0)
{
Eveniment ev = new Eveniment();
ev.setZiua(zi);
ev.setLuna(luna);
myAr.add(ev);
}
}
String l = new String();
l = "Ianuarie";
System.out.println(myAr.size());*/
for(int i = 0; i < myAr.size(); i++){
if(myAr.get(i).getLuna().equals(l))
System.out.println(1);
else
System.out.println(0);
}
}
public static void afisare(ArrayList<Eveniment> myAr){
System.out.println("---------Array------------");
for(Eveniment i : myAr){
System.out.println(i.getLuna() +" "+i.getZiua());
}
}
}
The thing that bugs me is that inside the for I do a check if a current object has it's luna string equal to l string then I print out 1 else I print 0, but the algorithm prints out 0 even if the strings are equal, what am I doing wrong ?
I'm a newbie with Java so please don't judge too harshly.
Input given to the program:
1 Decembrie
2 Ianuarie
3 Februarie
4 Martie
0//to end the input
The program should write
`Decembrie` 0
`Ianuarie` 1
`Februarie` 0
`Martie` 0
because l is equal to Ianuarie.
this is because
l = "Ianuarie"
and
myAr.get(i).getLuna() =" Ianuarie"
^--->there are space before the Ianuarie
so you will never get 1

How can I make array of bowlers?

Following is the question which I am trying to solve-
In a one day international, the bowling figures of all the bowlers have been provided. The objective is to create an array of Bowler and return it. Note that the objects should appear in the same order in the array as they appear in the input.
The input is provided a string. The string has space demarcated details of each bowler provided as Name-Overs-Maiden-Runs-Wickets, like , “Zaheer-10-1-55-0 Harbhajan-8.4-0-44-2 Ishant-10-0-71-1″.Define a function that takes and prints the array of Bowler returned.
There is some error in the code but I am unable to detect it.
public class MakeArrayOfBowlers{
String name;
double over;
int maiden;
int runs;
int wickets;
public MakeArrayOfBowlers(String input){
String[] str=input.split("-");
this.name=str[0];
this.over=Double.parseDouble(str[1]);
this.maiden=Integer.parseInt(str[2]);
this.runs=Integer.parseInt(str[3]);
this.wickets=Integer.parseInt(str[4]);
}
public MakeArrayOfBowlers[] makeBowlers (String input){
MakeArrayOfBowlers str= (MakeArrayOfBowlers) new MakeArrayOfBowlers("Zaheer-10-1-55-0 Harbhajan-8.4-0-44-2 Ishant-10-0-71-1");
String[] str1 = input.split(" ");
MakeArrayOfBowlers bowler[]= new MakeArrayOfBowlers[str1.length];
for(int i = 0; i < str1.length; i++){
bowler = new MakeArrayOfBowlers[str1.length];
MakeArrayOfBowlers obj = new MakeArrayOfBowlers(str1[i]);
bowler[i] = obj;
}
return bowler;
}
}
You should make a own class bowler (constructor should be better but its your example ;)):
public class Bowler {
private String name;
private double over;
private int maiden;
private int runs;
private int wickets;
public Bowler(String input){
String[] str=input.split("-");
this.name=str[0];
this.over=Double.parseDouble(str[1]);
this.maiden=Integer.parseInt(str[2]);
this.runs=Integer.parseInt(str[3]);
this.wickets=Integer.parseInt(str[4]);
}
public String getName() {
return name;
}
public double getOver() {
return over;
}
public int getMaiden() {
return maiden;
}
public int getRuns() {
return runs;
}
public int getWickets() {
return wickets;
}
}
Than split your string and add it for every bowler:
public class MakeArrayOfBowlers {
public static Bowler[] makeBowlers(String input) {
String[] splitArray = input.split(" ");
Bowler[] bowler = new Bowler[splitArray.length];
for (int i = 0; i < splitArray.length; i++) {
bowler[i] = new Bowler(splitArray[i]);
}
return bowler;
}
public static void main(String[] args) {
Bowler[] bowlers = makeBowlers("Zaheer-10-1-55-0 Harbhajan-8.4-0-44-2 Ishant-10-0-71-1");
for (Bowler bowler : bowlers) {
System.out.println(bowler.getName()+"-"+bowler.getOver()+"-"+bowler.getMaiden()+"-"+bowler.getRuns()+"-"+bowler.getWickets());
}
}
}
You're re-initializing the bowler array inside the for-loop. Try removing that line (the first line inside your loop).
public MakeArrayOfBowlers[] makeBowlers (String input){
String[] str1 = input.split(" ");
MakeArrayOfBowlers bowlers[]= new MakeArrayOfBowlers[str1.length];
for(int i = 0; i < str1.length; i++){
MakeArrayOfBowler bowler = new MakeArrayOfBowlers(str1[i]);
bowlers[i] = obj;
}
return bowlers;
}
From your main function call
MakeArrayOfBowlers o = new MakeArrayOfBowlers();
MakeArrayOfBowlers[] b = o.makeBowlers("Zaheer-10-1-55-0 Harbhajan-8.4-0-44-2 Ishant-10-0-71-1");

java method error

I have a task to do, which is make a film archive. Here are my tasks:
Besides the main program, create a custom class that stores information about a movie. This class is then used in the main program. The following information should be stored for each film
title
length
grade
format
year
then
In the main program, you should be able to store 1,000 films.
The user should be able to do the following in the program (make a selection menu):
• Enter the information about a movie. Make a method for loading a movie from the user.
• Print the information on all films. Make a method for printing a film and use it.
• Save all your movies to a file. Please do your own method for this.
• Download movies from a file. Please do your own method for this.
The problem is that I got an error with my skrivUtInfo(PrintOut information) method
I create an array list of 1000 films. But how can I print 1000 films?
Here is my code:
public class Film {
String title ;
int length;
int grade ;
String format ;
int year ;
}
import java.util.*;
import java.io.*;
public class Filmarkiv {
static Scanner sc = new Scanner(System.in);
public static void main(String[] arg) {
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Scanner s = new Scanner(inFromUser);
Film[] film = new Film[1000];
int antal = 1;
film[0] = new Film();
film[0].title = "matrix";
film[0].length = 220;
film[0].grade = 5;
film[0].format = "DVD";
film[0].year = 1999;
while(true)
{
int n = 0;
System.out.println("valj 1 for inmata. 2 for utskrift");
String val = s.next();
if(val.equals("1")){
System.out.println("vad heter filmen?");
film[n].title = s.next();
System.out.println("hur lang ar filmen?");
film[n].length = s.nextInt();
System.out.println("vad har den for betyg?");
film[n].grade = s.nextInt();
System.out.println("vad har den for format?");
film[n].format = s.next() ;
System.out.println("i vilket år har filmen inspelat? ");
film[n].year = s.nextInt() ;
}
else if (val.equals("2"))
{
skrivUtInfo(film, antal);
/*System.out.println("title = "+film[n].title) ;
System.out.println("length = "+film[n].length) ;
System.out.println("grade = "+film[n].grade) ;
System.out.println("format = "+film[n].format) ;
System.out.println("year = "+film[n].year);*/
}
}
}
public skrivUtInfo (Film[] qwert, int a) {
for (int n=0; n<a; n++) {
System.out.println("title = "+film[n].title) ;
System.out.println("length = "+film[n].length) ;
System.out.println("grade = "+film[n].grade) ;
System.out.println("format = "+film[n].format) ;
System.out.println("year = "+film[n].year) ;
return Film[];
}
}
}
you have to change the method as
public static void skrivUtInfo (Film[] qwert) {
for (int n=0; n<qwert.length; n++) {
System.out.println("title = "+qwert[n].title) ;
System.out.println("length = "+qwert[n].length) ;
System.out.println("grade = "+qwert[n].grade) ;
System.out.println("format = "+qwert[n].format) ;
System.out.println("year = "+qwert[n].year) ;
}
}
also put a bracket here
else if (val.equals("2"))
{
skrivUtInfo(film);
// the comments
}
} //<- you must add this bracket. is from while (i think)
also a tip, in Film class you can override the toString method from class Object
public class Film{
String title ;
int length;
int grade ;
String format ;
int year ;
public String toString() {
return "title = " + title +
"length = " + length +
"grade = " + grade +
"format = " + format +
"year = " + year;
}
}
so the skrivUtInfo becomes
public static void skrivUtInfo (Film[] qwert) {
for (int n=0; n<qwert.length; n++) {
System.out.println(qwert[n]);
}
}
or
public static void skrivUtInfo (Film[] qwert) {
for (Film f : qwert) {
System.out.println(f);
}
}
If you've learned about java.util.List, you can do it this way:
List<Film> films = new ArrayList<Film>();
films.add(new Film("Amadeus", 120, 5, "DVD", 1984); ); // Add as many as you like
System.out.println(films); // Make sure your Film class overrides toString()
If you haven't, just do it in a loop:
Film [] films = new Film[1000];
films[0] = new Film("Amadeus", 120, 5, "DVD", 1984);
for (Film film : films) {
System.out.println(film); // Make sure you File class overrides toString()
}
You're probably having problems because your Film class is flawed. Do it this way:
public class Film {
private final String title ;
private final int length;
private final int grade ;
private final String format ;
private final int year ;
public Film(String title, int length, int grade, String format, int year) {
this.title = title;
this.length = length;
this.grade = grade;
this.format = format;
this.year = year;
}
public String getTitle() {
return title;
}
public int getLength() {
return length;
}
public int getGrade() {
return grade;
}
public String getFormat() {
return format;
}
public int getYear() {
return year;
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("Film");
sb.append("{title='").append(title).append('\'');
sb.append(", length=").append(length);
sb.append(", grade=").append(grade);
sb.append(", format='").append(format).append('\'');
sb.append(", year=").append(year);
sb.append('}');
return sb.toString();
}
}
The method public skrivUtInfo (Film[] qwert, int a) has no return type specified. In java either it should have a void or a valid type as return, but i see you returning Film[]. You cannot do that way. You have to declare like
public Film[] skrivUtInfo (Film[] qwert, int a){
....
return qwert;
}
Ultimately since you are just printing the stuff here you don't need to return anything. In that case you should have
public void skrivUtInfo (Film[] qwert, int a){
.....
return;
}
You can have an empty return or no return specified in a method which has a void return type.
I have test this code and works fine. I change a few parts as i thought it should play
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Filmarkiv {
static Scanner sc = new Scanner(System.in);
public static void main(String[] arg) {
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Scanner s = new Scanner(inFromUser);
Film[] film = new Film[1000];
int n = 0;
do {
System.out.println("valj 1 for inmata. 2 for utskrift");
String val = s.next();
if (val.equals("1")) {
film[n] = new Film();
System.out.println("vad heter filmen?");
film[n].title = s.next();
System.out.println("hur lang ar filmen?");
film[n].length = s.nextInt();
System.out.println("vad har den for betyg?");
film[n].grade = s.nextInt();
System.out.println("vad har den for format?");
film[n].format = s.next();
System.out.println("i vilket år har filmen inspelat? ");
film[n].year = s.nextInt();
n++;
} else if (val.equals("2")) {
skrivUtInfo(film);
}
} while(n < film.length);
}
public static void skrivUtInfo (Film[] qwert) {
for (Film f : qwert) {
if (f != null)
System.out.println(f);
}
}
}
class Film {
String title;
int length;
int grade;
String format;
int year;
public String toString() {
return "title = " + title + ", length = " + length + ", grade = " + grade
+ ", format = " + format + ", year = " + year;
}
}

Categories