Use File IO and make data shows in clear way - java

I try use file IO declare obj that I create for baseball team information, but I dont know why the arrayList save the same data again and again, I want each data save once in arraylist. thank you
public static void main(String[] args) throws IOException{
Scanner in = new Scanner(System.in);
String fileName = "abc.txt"; //file name
// System.out.println("Please Enter The Source File Name:: ");
// fileName = in.nextLine();
ArrayList<Team> group = new ArrayList<Team>(); //use arrayList save data from obj
File file = new File(fileName); //open file
Scanner scan = new Scanner(file);
while (scan.hasNext()) { //read file to string and split it
String str = scan.nextLine();
String[] arr = str.split(",");
for (int i = 0; i < file.length(); i++) { //use split part to declear obj"Team"
int n = Integer.parseInt(arr[3]);
int m = Integer.parseInt(arr[4]);
Team tm = new Team(arr[0], arr[1], arr[2], n, m);
group.add(tm);
}
// scan.close();
//try to close but shows error"Scanner closed"
}
for(int i =0; i < group.size(); i++) { //check arrayList work well, but fail
System.out.println(group.get(i).getName());
}
}

In your code, for loop inside while loop seems to make duplicated entries
while (scan.hasNext()) { //read file to string and split it
String str = scan.nextLine();
String[] arr = str.split(",");
int n = Integer.parseInt(arr[3]);
int m = Integer.parseInt(arr[4]);
Team tm = new Team(arr[0], arr[1], arr[2], n, m);
group.add(tm);
}

**try this :**
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class SureshTemp
{
public static void main(String[] args) {
BufferedReader bf=null;
ArrayList al=new ArrayList();
try
{
String currentLine;
bf=new BufferedReader(new FileReader("D:\\abc.txt"));
while((currentLine=bf.readLine())!=null)
{
System.out.println(currentLine);
String str=currentLine;
String[] arr=str.split(",");
int n=Integer.parseInt(arr[3]);
int m=Integer.parseInt(arr[4]);
Team t=new Team(arr[0],arr[1], arr[2], n, m);
al.add(t);
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try {
if (bf != null)bf.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
for(int i =0; i < al.size(); i++){
System.out.println(al.get(i));
}
}
}
class Team
{
private String First;
private String next;
private String third;
private int won;
private int lost;
public Team(String F,String N,String T,int w,int l)
{
First=F;
next=N;
third=T;
won=w;
lost=l;
}
#Override
public String toString() {
return "Team [First=" + First + ", next=" + next + ", third=" + third
+ ", won=" + won + ", lost=" + lost + "]";
}
public String getFirst() {
return First;
}
public void setFirst(String first) {
First = first;
}
public String getNext() {
return next;
}
public void setNext(String next) {
this.next = next;
}
public String getThird() {
return third;
}
public void setThird(String third) {
this.third = third;
}
public int getWon() {
return won;
}
public void setWon(int won) {
this.won = won;
}
public int getLost() {
return lost;
}
public void setLost(int lost) {
this.lost = lost;
}
}

try this :
while (scan.hasNext()) {
String str = scan.nextLine();
String[] arr = str.split(",");
int n = Integer.parseInt(arr[3]);
int m = Integer.parseInt(arr[4].trim()); // Use trim()to avoid NumberFormatException
Team tm = new Team(arr[0], arr[1], arr[2], n, m);
group.add(tm);
}

Related

how to get particular element from ArrayList

Hello I am solving this problem given to me where I have to find average salary of a person which has least index id
import java.util.*;
import java.io.*;
public class Main {
public static int processData(ArrayList<String> array) {
for (String elem :array){
System.out.println(elem);
}
return 0;
}
public static void main (String[] args) {
ArrayList<String> inputData = new ArrayList<String>();
try {
Scanner in = new Scanner(new BufferedReader(new FileReader("input.txt")));
while(in.hasNextLine()) {
String line = in.nextLine().trim();
if (!line.isEmpty()) // Ignore blank lines
inputData.add(line);
}
int retVal = processData(inputData);
PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
output.println("" + retVal);
output.close();
} catch (IOException e) {
System.out.println("IO error in input.txt or output.txt");
}
}
}
the program is accepting input from text file as follows
282, ij, 11, 1600000
273, cbg, 12, 800000
567, nj, 11, 800000
539, cb, 11, 600000
So the output will be
11 520000
I am able to print the elements from array list but not been able to access particular elements. Can anyone help me to access particular element which is, in this case, 11,160000 and so on?
Thank you in advance
Hint
You can calculate the AVG of the index 11 like this :
public static int processData(ArrayList<String> array) {
String[] spl;
int avg = 0, nbr = 0;
for (String elem : array) {
//split your String with ", " and space
spl = elem.split(", ");
//the index exist in the 3ed position, so you have to check your index if 11 then you can get its value
if(spl[2].equals("11")){
avg+=Integer.parseInt(spl[3]);
nbr++;
}
System.out.println(elem);
}
System.out.println((avg/nbr));
return avg / nbr;
}
When you print in your code you have to use :
output.println("11 " + retVal);
Hope this can gives you an idea.
You create a List of String to store employee data that contains multiple fields.
You should not as it mixes data employees.
The general idea I propose you :
1) Instead of storing all information in a List of String, use a List of Employee.
replace
ArrayList<String> inputData = new ArrayList<String>();
by
List<Employee> employees = new ArrayList<Employee>();
2)Use each read line that represents a person to create a instance of a custom Object, for example Employee.
So replace
inputData.add(line);
by something like that
String[] token = line.split(",");
Employee employee= new Employee(Integer.valueOf(token[0]),token[1],Integer.valueOf(token[2]),Integer.valueOftoken[3]));
employees.add(employee);
3) During this iteration to read the file, you can store in a variable that is the Employee with the minimum id.
4) After reading the file, you know the Employee with the minimum id. So you can iterate on the List of Employee and sum the salaries of the Employee that has this id and count the number of salary for this Employee.
When the loop is finished compute the avg : float avg = sum / (float)count;
It is not the most optimized way but it makes the job.
The following code will do what you need.
public class MyMain {
private static String inputFilePath = "/path/to/input.txt";
private static String outputFilePath = "/path/to/output.txt";
public static int processData(ArrayList<MyData> array) {
if (array.size() > 0) {
int minId = array.get(0).getData3();
for (MyData elem : array) {
if(elem.getData3() < minId) {
minId = elem.getData3();
}
}
int count = 0;
int total = 0;
for (MyData myData : array) {
if(myData.getData3() == minId) {
count++;
total += myData.getData4();
}
}
System.out.println("Min ID : " + minId + " -- Avg Sal : " + total/count);
}
return 0;
}
public static void main(String[] args) {
ArrayList<MyData> inputData = new ArrayList<>();
try {
Scanner in = new Scanner(new BufferedReader(new FileReader(inputFilePath)));
while (in.hasNextLine()) {
String line = in.nextLine().trim();
if (!line.isEmpty()) // Ignore blank lines
inputData.add(new MyData(line));
}
int retVal = processData(inputData);
PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter(outputFilePath)));
output.println("" + retVal);
output.close();
} catch (IOException e) {
System.out.println("IO error in input.txt or output.txt");
}
}
}
class MyData {
int data1;
String data2;
int data3;
int data4;
public MyData() {
// TODO Auto-generated constructor stub
}
public MyData(String data) {
String dataArr[] = data.split(",");
this.data1 = Integer.parseInt(dataArr[0].trim());
this.data2 = dataArr[1].trim();
this.data3 = Integer.parseInt(dataArr[2].trim());
this.data4 = Integer.parseInt(dataArr[3].trim());
}
public int getData1() {
return data1;
}
public void setData1(int data1) {
this.data1 = data1;
}
public String getData2() {
return data2;
}
public void setData2(String data2) {
this.data2 = data2;
}
public int getData3() {
return data3;
}
public void setData3(int data3) {
this.data3 = data3;
}
public int getData4() {
return data4;
}
public void setData4(int data4) {
this.data4 = data4;
}
}

why my program don't recognize the .txt file

I try to made a program which print the top 20 frequently words in a text file in java, and i have 3 classes but i don't know why can not compile it help me please. I show you the tree classes just to have an idea:
1)
public class Client {
public static void main(String[] args) {
Map<String, Integer> frequencies = new TreeMap<String, Integer>();
while(file.hasNext()){//Este lazo lee las palabras y crea el TreeMap
String word= clean(doc.next());
Integer count = frequencies.get(word);
if(count==null){
count = 1;}
else {
count = count + 1;
}
}
Object[] Claves = frequencies.keySet().toArray();
Object[] Valores = frequencies.values().toArray();
Par[] par = new Par[frequencies.size()];
for (int i=0;i<frequencies.size();i++){
Par p = new Par(Claves[i].toString(),(int) Valores[i]);
par[i]=p;
}
Arrays.sort(par);
showResult(par);
}
public static void showResult(Par[] arreglo){
System.out.println("The 20 most frequently words are ");
for(int i= 0; i<=19; i++){
System.out.print("Word "+ arreglo[i].Clave + " in " + arreglo[i].Valor + " times.");
}
}
}
2)
public class Par implements Comparable {
String Clave;
int Valor;
public int length;
public Par(String clave, int valor){
this.Clave = clave;
this.Valor = valor;
}
public int compareTo(Par p) {
if(this.Valor<p.Valor){
return 1;
}
else if(this.Valor==p.Valor){
return 0;
}
else{
return -1;
}
}
}
3)
public class ProcessText {
public void reader(Path r){
String name = clean(file.getName());
if(file.getName().equals(name + ".txt" || file.getName().equals(name + ".doc" ))){
try (Scanner sc = new Scanner(r)){
String doc = "";
while(sc.hasNextLine()){
String linea = (sc.nextLine());
doc = doc.concat(linea + "\n");
}
sc.close();
}
}
}
public static String clean(String s){
String r = "";
for (int i=0;i<s.length();i++){
char c = s.charAt(i);
if (Character.isLetter(c)){
r = r + c;
}
}
return r.toLowerCase();
}
}
If this is all the code you have, your problem might be that your main method never creates a variable called "doc" or "file", but you use them both at the beginning of Client's main method.
It would be more helpful if you could share the compile time error, though, so I can't be sure that this is your problem.

How to print the first 10 lines from an enhanced for loop

I have a file with over 1000 names it also include the sex and how many people have the name.
example
Sarah F 2000
I am trying to print the first 10 lines that was created from my for loop, but for some reason what i tried is only printing the last line 10 times.
import java.util.*;
import java.io.*;
import java.util.Collections;
public class NameYear
{
private String year;
ArrayList<OneName> oneName = new ArrayList<OneName>();
public NameYear(String year)
{
String line = "";
String Top = "";
Scanner sc = null;
try
{
sc = new Scanner(new File
("/home/mathcs/courses/cs225/koch/names/yob"+year+".txt"));
}
catch (Exception e)
{
System.out.println("Error Year should be between 1880 and 2013 not "+ year);
System.exit(1);
}
while(sc.hasNextLine())
{
// read a line from the input file via sc into line
line = sc.nextLine();
StringTokenizer stk = new StringTokenizer(line, ",");
String name = stk.nextToken();
char sex = stk.nextToken().charAt(0);
int count = Integer.parseInt(stk.nextToken());
OneName list = new OneName(name, sex, count);
oneName.add(list);
}
for (int i = 0 ; i < 10; i++)
{
System.out.println(descending());
}
public String descending()
{
String x = "";
Collections.sort(oneName, new OneNameCountCompare());
for(OneName b: oneName)
{
x = b.toString();
}
return x;
OneName file
public class OneName
{
private String Name;
private char Sex;
private int Count;
public OneName(String name, char sex, int count)
{
Name = name;
Sex = sex;
Count = count;
}
public String getName()
{
return Name;
}
public char getSex()
{
return Sex;
}
public int getCount()
{
return Count;
}
public void setName(String name)
{
if (name.length() < 1)
{
throw new NullPointerException("Baby name is missing");
}
Name = name;
}
private char M;
private char F;
public void setSex(char sex)
{
if( sex != M)
{
if(sex != F)
{
throw new IllegalArgumentException("Sex has to be M or F");
}
}
Sex = sex;
}
public void setCount(int count)
{
if(count < 0)
{
throw new IllegalArgumentException("Count cant be negative");
}
Count = count;
}
public String toString()
{
return String.format("%s %c %d", Name, Sex, Count);
}
}
OneNameCount
import java.util.Comparator;
import java.util.Collections;
public class OneNameCountCompare implements Comparator<OneName>
{
public int compare(OneName b1, OneName b2)
{
if(b1.getCount() <b2.getCount())
{
return 1;
}
else
{
return -1;
}
}
}
Main Program
import java.io.*;
import java.util.*;
public class TopNames
{
public static void main(String args[])
{
String line = ""; // string var to hold entire line
if (args.length < 1)
{
System.out.println("\nYou forgot to put a Year on the command line.");
System.exit(1);
};
String inFile = args[0]; // file name off command line
String year = inFile;
NameYear list = new NameYear(year);
}
}
Your descending function returns one string, and always the same string (the last one in the order after sorting the collection). It doesn't matter how often you call it, if the data doesn't change, you'll always get back that same, last, string.
If you want the first 10 after sorting, descending would need to return a List<String> containing those 10:
public List<String> descending()
{
List<String> x = new ArrayList<String>(10);
Collections.sort(oneName, new OneNameCountCompare());
for(OneName b: oneName)
{
x.add(b.toString());
if (x.size() == 10) // Or don't use enhanced for, use an index instead
{
break;
}
}
return x;
}
Then when printing it, replace your for (int i = 0 ; i < 10; i++) loop with:
for (String s : descending())
{
System.out.println(s);
}
Your error is here:
for (int i = 0 ; i < 10; i++) {
System.out.println(descending());
}
public String descending() {
String x = "";
Collections.sort(oneName, new OneNameCountCompare());
for(OneName b: oneName) {
x = b.toString();
}
return x;
}
First of all in your for loop you are not using the i variable that is your count indicator. This means that the descending() method has no any awareness of i, how he could return something different?
Try to modify descending() in something like this:
public String descending(int i) {
String x = "";
Collections.sort(oneName, new OneNameCountCompare());
OneName b = oneName.get(i);
x = b.toString();
return x;
}

Writing on an output file

I am stuck on this part where it does not write to an output file
the first class is contact I had to modify this is not my class is the authors class
I just had to use it
//********************************************************************
// Contact.java Author: Lewis/Loftus
//
// Represents a phone contact.
//********************************************************************
public class Contact implements Comparable
{
private String firstName, lastName, phone;
//-----------------------------------------------------------------
// Constructor: Sets up this contact with the specified data.
//-----------------------------------------------------------------
public Contact (String first, String last, String telephone)
{
firstName = first;
lastName = last;
phone = telephone;
}
//-----------------------------------------------------------------
// Returns a description of this contact as a string.
//-----------------------------------------------------------------
public String toString ()
{
return lastName + ", " + firstName + "\t" + phone;
}
//-----------------------------------------------------------------
// Returns true if the first and last names of this contact match
// those of the parameter.
//-----------------------------------------------------------------
public boolean equals (Object other)
{
return (lastName.equals(((Contact)other).getLastName()) &&
firstName.equals(((Contact)other).getFirstName()));
}
//-----------------------------------------------------------------
// Uses both last and first names to determine ordering.
//-----------------------------------------------------------------
public int compareTo (Object other)
{
int result;
String otherFirst = ((Contact)other).getFirstName();
String otherLast = ((Contact)other).getLastName();
if (lastName.equals(otherLast))
result = firstName.compareTo(otherFirst);
else
result = lastName.compareTo(otherLast);
return result;
}
//-----------------------------------------------------------------
// First name accessor.
//-----------------------------------------------------------------
public String getFirstName ()
{
return firstName;
}
//-----------------------------------------------------------------
// Last name accessor.
//-----------------------------------------------------------------
public String getLastName ()
{
return lastName;
}
}
this class oes the sorting this is fine. it does the sorting no prblem
public class Sorting {
public static void bubbleSortRecursive(Comparable[] data, int n)
{
if (n < 2)
{
return;
}
else
{
int lastIndex = n - 1;
for (int i = 0; i < lastIndex; i++)
{
if (data[i].compareTo(data[i + 1]) > 0)
{ //swap check
Comparable tmp = data[i];
data[i] = data[i + 1];
data[i + 1] = tmp;
}
}
bubbleSortRecursive(data, lastIndex);
}
}
public static void selectionSortRecursive(Comparable[] data, int n)
{
if (n < 2)
{
return;
}
else
{
int lastIndex = n - 1;
int largestIndex = lastIndex;
for (int i = 0; i < lastIndex; i++)
{
if (data[i].compareTo(data[largestIndex]) > 0)
{
largestIndex = i;
}
}
if (largestIndex != lastIndex)
{ //swap check
Comparable tmp = data[lastIndex];
data[lastIndex] = data[largestIndex];
data[largestIndex] = tmp;
}
selectionSortRecursive(data, n - 1);
}
}
}
this is the part I need help with. It is not outputing to he p4output.txt, i dont know what the problem is.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class TestProject4 {
public static void main(String[] args)
{
doBubbleSortRecursive();
System.out.println();
System.out.println();
doSelectionSortRecursive();
}
private static void doBubbleSortRecursive()
{
Contact[] contacts = createContacts();
System.out.println("Before bubbleSortRecursive(): ");
for (int i=0; i<contacts.length; i++)
System.out.println(contacts[i].toString());
Sorting.bubbleSortRecursive(contacts, contacts.length);
System.out.println("\nAfter bubbleSortRecursive(): ");
for (int i=0; i<contacts.length; i++)
System.out.println(contacts[i].toString());
}
private static void doSelectionSortRecursive()
{
Contact[] contacts = createContacts();
System.out.println("Before selectionSortRecursive(): ");
for (int i=0; i<contacts.length; i++)
System.out.println(contacts[i].toString());
Sorting.selectionSortRecursive(contacts, contacts.length);
System.out.println("\nAfter selectionSortRecursive(): ");
for (int i=0; i<contacts.length; i++)
System.out.println(contacts[i].toString());
}
private static void printContacts(Contact[] contacts)
{
try
{
// this part I need help with it is not outputing in the text file
File file = new File("p4output.txt");
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
for (Contact contact : contacts)
{
bw.write(contact.toString());
}
bw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println("\t" + contacts);
}
public static Contact[] createContacts()
{
return new Contact[]
{
new Contact("John" , "Smith" , "610-555-7384"),
new Contact("Sarah" , "Barnes" , "215-555-3827"),
new Contact("Mark" , "Riley", "333-333-3333"),
new Contact("Laura" , "Getz" ,"663-555-3984"),
new Contact("Larry" , "Smith" , "464-555-3489"),
new Contact("Frank" , "Phelps" , "322-555-2284"),
new Contact("Mario" , "Guzman" , "804-555-9066"),
new Contact("Marsha" , "Grant" , "243-555-2837"),
};
}
}
According to Eclipse, you never call/use printContacts(Contact[] contacts); method
Your printContacts(Contact[] contacts); contains the statements to write a file.
You don't appear to call the function printContacts() in your program. Try calling it after you do your contact creation and sorting.
It might look like this:
public static void main(String[] args)
{
doBubbleSortRecursive();
System.out.println();
System.out.println();
doSelectionSortRecursive();
printContacts(contactArray);//inserted code
}
Also, when you call your sorting methods, doSelectionSortRecursive(), you don't return the list of contacts. Make a return statement for it and then put the contact array into your printContacts function.
Here's an example:
public static void main(String[] args)
{
doBubbleSortRecursive();
System.out.println();
System.out.println();
Contact[] contacts = doSelectionSortRecursive();
printContacts(contacts);
}
public static Contact[] doSelectionSortRecursive(){
Contact[] contacts = createContacts();
//your sorting code
return contacts;
}
Using this method allows you to get the array of contacts from the method once it has been sorted.

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