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.
Related
I'm building a classifier which has to read through a lot of textdocuments, but I found out that my countWordFrequenties method gets slower the more documents it has processed. This method underneath takes 60ms (on my PC), while reading, normalizing, tokenizing, updating my vocabulary and equalizing of different lists of integers only takes 3-5ms in total (on my PC). My countWordFrequencies method is as follows:
public List<Integer> countWordFrequencies(String[] tokens)
{
List<Integer> wordFreqs = new ArrayList<>(vocabulary.size());
int counter = 0;
for (int i = 0; i < vocabulary.size(); i++)
{
for (int j = 0; j < tokens.length; j++)
if (tokens[j].equals(vocabulary.get(i)))
counter++;
wordFreqs.add(i, counter);
counter = 0;
}
return wordFreqs;
}
What is the best way for me to speed this process up? What is the problem of this method?
This is my entire Class, there is another Class Category, is it a good idea to post this also here or don't you guys need it?
public class BayesianClassifier
{
private Map<String,Integer> vocabularyWordFrequencies;
private List<String> vocabulary;
private List<Category> categories;
private List<Integer> wordFrequencies;
private int trainTextAmount;
private int testTextAmount;
private GUI gui;
public BayesianClassifier()
{
this.vocabulary = new ArrayList<>();
this.categories = new ArrayList<>();
this.wordFrequencies = new ArrayList<>();
this.trainTextAmount = 0;
this.gui = new GUI(this);
this.testTextAmount = 0;
}
public List<Category> getCategories()
{
return categories;
}
public List<String> getVocabulary()
{
return this.vocabulary;
}
public List<Integer> getWordFrequencies()
{
return wordFrequencies;
}
public int getTextAmount()
{
return testTextAmount + trainTextAmount;
}
public void updateWordFrequency(int index, Integer frequency)
{
equalizeIntList(wordFrequencies);
this.wordFrequencies.set(index, wordFrequencies.get(index) + frequency);
}
public String readText(String path)
{
BufferedReader br;
String result = "";
try
{
br = new BufferedReader(new FileReader(path));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null)
{
sb.append(line);
sb.append("\n");
line = br.readLine();
}
result = sb.toString();
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
return result;
}
public String normalizeText(String text)
{
String fstNormalized = Normalizer.normalize(text, Normalizer.Form.NFD);
fstNormalized = fstNormalized.replaceAll("[^\\p{ASCII}]","");
fstNormalized = fstNormalized.toLowerCase();
fstNormalized = fstNormalized.replace("\n","");
fstNormalized = fstNormalized.replaceAll("[0-9]","");
fstNormalized = fstNormalized.replaceAll("[/()!?;:,.%-]","");
fstNormalized = fstNormalized.trim().replaceAll(" +", " ");
return fstNormalized;
}
public String[] handleText(String path)
{
String text = readText(path);
String normalizedText = normalizeText(text);
return tokenizeText(normalizedText);
}
public void createCategory(String name, BayesianClassifier bc)
{
Category newCategory = new Category(name, bc);
categories.add(newCategory);
}
public List<String> updateVocabulary(String[] tokens)
{
for (int i = 0; i < tokens.length; i++)
if (!vocabulary.contains(tokens[i]))
vocabulary.add(tokens[i]);
return vocabulary;
}
public List<Integer> countWordFrequencies(String[] tokens)
{
List<Integer> wordFreqs = new ArrayList<>(vocabulary.size());
int counter = 0;
for (int i = 0; i < vocabulary.size(); i++)
{
for (int j = 0; j < tokens.length; j++)
if (tokens[j].equals(vocabulary.get(i)))
counter++;
wordFreqs.add(i, counter);
counter = 0;
}
return wordFreqs;
}
public String[] tokenizeText(String normalizedText)
{
return normalizedText.split(" ");
}
public void handleTrainDirectory(String folderPath, Category category)
{
File folder = new File(folderPath);
File[] listOfFiles = folder.listFiles();
if (listOfFiles != null)
{
for (File file : listOfFiles)
{
if (file.isFile())
{
handleTrainText(file.getPath(), category);
}
}
}
else
{
System.out.println("There are no files in the given folder" + " " + folderPath.toString());
}
}
public void handleTrainText(String path, Category category)
{
long startTime = System.currentTimeMillis();
trainTextAmount++;
String[] text = handleText(path);
updateVocabulary(text);
equalizeAllLists();
List<Integer> wordFrequencies = countWordFrequencies(text);
long finishTime = System.currentTimeMillis();
System.out.println("That took 1: " + (finishTime-startTime)+ " ms");
long startTime2 = System.currentTimeMillis();
category.update(wordFrequencies);
updatePriors();
long finishTime2 = System.currentTimeMillis();
System.out.println("That took 2: " + (finishTime2-startTime2)+ " ms");
}
public void handleTestText(String path)
{
testTextAmount++;
String[] text = handleText(path);
List<Integer> wordFrequencies = countWordFrequencies(text);
Category category = guessCategory(wordFrequencies);
boolean correct = gui.askFeedback(path, category);
if (correct)
{
category.update(wordFrequencies);
updatePriors();
System.out.println("Kijk eens aan! De tekst is succesvol verwerkt.");
}
else
{
Category correctCategory = gui.askCategory();
correctCategory.update(wordFrequencies);
updatePriors();
System.out.println("Kijk eens aan! De tekst is succesvol verwerkt.");
}
}
public void updatePriors()
{
for (Category category : categories)
{
category.updatePrior();
}
}
public Category guessCategory(List<Integer> wordFrequencies)
{
List<Double> chances = new ArrayList<>();
for (int i = 0; i < categories.size(); i++)
{
double chance = categories.get(i).getPrior();
System.out.println("The prior is:" + chance);
for(int j = 0; j < wordFrequencies.size(); j++)
{
chance = chance * categories.get(i).getWordProbabilities().get(j);
}
chances.add(chance);
}
double max = getMaxValue(chances);
int index = chances.indexOf(max);
System.out.println(max);
System.out.println(index);
return categories.get(index);
}
public double getMaxValue(List<Double> values)
{
Double max = 0.0;
for (Double dubbel : values)
{
if(dubbel > max)
{
max = dubbel;
}
}
return max;
}
public void equalizeAllLists()
{
for(Category category : categories)
{
if (category.getWordFrequencies().size() < vocabulary.size())
{
category.setWordFrequencies(equalizeIntList(category.getWordFrequencies()));
}
}
for(Category category : categories)
{
if (category.getWordProbabilities().size() < vocabulary.size())
{
category.setWordProbabilities(equalizeDoubleList(category.getWordProbabilities()));
}
}
}
public List<Integer> equalizeIntList(List<Integer> list)
{
while (list.size() < vocabulary.size())
{
list.add(0);
}
return list;
}
public List<Double> equalizeDoubleList(List<Double> list)
{
while (list.size() < vocabulary.size())
{
list.add(0.0);
}
return list;
}
public void selectFeatures()
{
for(int i = 0; i < wordFrequencies.size(); i++)
{
if(wordFrequencies.get(i) < 2)
{
vocabulary.remove(i);
wordFrequencies.remove(i);
for(Category category : categories)
{
category.removeFrequency(i);
}
}
}
}
}
Your method has O(n*m) run time ( n being the vocabulary size and m the token size). With hashing this could be reduced to O(m) which is clearly better.
for (String token: tokens) {
if(!map.containsKey(token)){
map.put(token,0);
}
map.put(token,map.get(token)+1);
}
Using a Map should dramatically increase performance, as Sleiman Jneidi suggested in his answer. This can be done, however, much more elegantly with Java 8's streaming APIs:
Map<String, Long> frequencies =
Arrays.stream(tokens)
.collect(Collectors.groupingBy(Function.identity(),
Collectors.counting()));
Instead of using a list for the vocabulary, and another one for the frequencies, I'd use a Map that will store word->frequency. That way you can avoid the double loop which in my mind is what kills your performance.
public Map<String,Integer> countWordFrequencies(String[] tokens) {
// vocabulary is Map<String,Integer> initialized with all words as keys and 0 as value
for (String word: tokens)
if (vocabulary.containsKey(word)) {
vocabulary.put(word, vocabulary.get(word)+1);
}
return vocabulary;
}
If you don't want to use Java 8 stuff you can try to use MultiSet from guava
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);
}
This is a homework of mine. However, I can't get the result to work. I want it to print out as:
> 2*7*6
2
* 7
----
14
* 6
----
84
and so on. I want the code to work regardless of how many numbers I type in. This is my code so far;
public static int add(int a, int b) {
return a + b;
}
public static int sub(int a, int b) {
return a - b;
}
public static int multiply(int a, int b) {
return a * b;
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("(ex. 8*2*6): ");
String amount = in.nextLine();
if ( amount.contains("+") ) {
String[] parts = amount.split("\\+");
} else if ( amount.contains("-") ) {
String[] parts = amount.split("\\-");
} else if ( amount.contains("*") ) {
String[] parts = amount.split("\\*");
int[] results = new int[parts.length];
// Convert from string to integer
for (int i = 0; i < parts.length; i++) {
try {
results[i] = Integer.parseInt(parts[i]);
} catch (NumberFormatException nfe) {};
}
// Print result
int counter = 1;
for (int i = 0; i <= results.length; i++) {
if ( i == 0) {
System.out.println(" " + results[i]);
System.out.println("* " + results[counter]);
System.out.println("----");
int total = multiply(results[i], results[counter]);
System.out.println(" " + total);
} else if ( i > 1 ) {
System.out.println("* " + results[i]);
System.out.println("----");
System.out.println(" " + multiply(results[i], results[counter]) );
}
}
} else {
System.out.println("Error");
}
What am I doing wrong?
Is not c# isn it? I'm not sure if i understand you.
In c#, have you tried something like that.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args) {
// Scanner in = new Scanner(System.in);
// String amount = Console.ReadLine();
String amount = "2*7*6*5*3*2";
if (amount.Contains('+')) {
String[] parts = amount.Split('+');
}
else
if (amount.Contains('-')) {
String[] parts = amount.Split('-');
}
else if (amount.Contains("*")) {
String[] parts = amount.Split('*');
int[] results = new int[parts.Length];
// Convert from string to integer
for (int i = 0; i < parts.Length; i++) {
try {
results[i] = int.Parse(parts[i]);
}
catch (FormatException nfe) { };
}
// Print result
int total = results[0];
for (int i = 1; i < results.Length; i++) {
if (i == 1)
Console.WriteLine(" " + results[i - 1]);
Console.WriteLine("* " + results[i]);
Console.WriteLine("----");
total = multiply(results[i], total);
Console.WriteLine(" " + total);
}
}
else {
Console.WriteLine("Error");
}
Console.ReadKey();
}
public static int add(int a, int b) {
return a + b;
}
public static int sub(int a, int b) {
return a - b;
}
public static int multiply(int a, int b) {
return a * b;
}
public static void main(String[] args) {
}
}
}
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.
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;
}
}