Array's elements' attributes in java - java

I am a newbie to Java. I have an array which includes sports IDs in int type. These IDs have sports name and calorie which burns if you do sport 1 hour. I want to add these attributes(name and calorie) through this array's elements. I am also reading a file that includes sports ID, name, and calorie information. I am splitting them by \t. It is splitting but the problem is, my implementation does not assign the attributes. I need to do this on Sports class not Main class. And I have to access this array and its attributes in other classes. If I give an example when I call array[2].name this must give me like Basketball. Or, array[2].calorie must give me 200. I have tried in for loop and assign them like:
for ( int i = 0; i < array.length; i++ ) {
array[i].name = nameOfSport;
array[i].calorie = calorieOfSport;
}
import java.io.*;
import java.util.*;
public class Sport {
private int sportID;
private String sportName;
private int sportCalorie;
public int[] sportArray = new int[0];
public void readFileSport() {
File file = new File("src/sport.txt");
try {
BufferedReader br = new BufferedReader(new FileReader(file));
int i = 0;
String str;
try {
while ((str = br.readLine()) != null) {
int j = 0;
for ( String retval: str.split("\t")) {
if ( j == 0 ) {
System.out.println(retval);
sportArray = addElementArray(sportArray, Integer.parseInt(retval));
System.out.println(sportArray[i]);
j++;
} else {
if (j == 1) {
// System.out.println(retval);
setSportName(sportArray, retval, i);
System.out.println(sportArray[i].sportName);
j++;
} else if (j == 2) {
//System.out.println(retval);
setSportCalorie(Integer.parseInt(retval));
j++;
}
}
}
i++;
}
} catch (FileNotFoundException e) {
System.out.println("Sport File could not find");
}
} catch (IOException e) {
System.out.println("Sport file could not read!");
}
}
public void assignFields () {
}
public void setSportID (int sportID) {
this.sportID = sportID;
}
public void setSportName (int[] array, String name, int e) {
array[e].sportName = name;
}
public void setSportCalorie (int sportCalorie) {
this.sportCalorie = sportCalorie;
}
public void print() {
int k = 0;
while ( k < sportArray.length ) {
System.out.println(sportID);
k++;
}
}
public static int[] addElementArray(int[] array, int newInt) {
int[] newArray = new int[array.length + 1];
for ( int i = 0 ; i < array.length ; i++ ) {
newArray[i] = array[i];
}
newArray[newArray.length - 1] = newInt;
return newArray;
}
public int[] getSportArray() {
return sportArray;
}
}

So let's say you have a class called Sports with
public class Sport{
public String name;
public int calorie;
}
Then you initiate them with
Sport[] sports = new Sport[] // or your own split() to specify length
Arrays.setAll(sports, i->new Sport())
And this should be able to solve the problem.
You can also use ArrayList in which you could just add new elements while looping through the lines.
public static void readFileSport() {
File file = new File("src/sport.txt");
try {
Scanner br = new Scanner(file);
int i = 0;
String str;
try {
while (br.hasNextLine()) {
String[] info=str.split("\t");
System.out.println(info[0]);
sportArray = addElementArray(sportArray, Integer.parseInt(info[0]));
System.out.println(sportArray[i]);
// System.out.println(info[1]);
setSportName(sportArray, info[1], i);
System.out.println(sportArray[i].sportName);
//System.out.println(info[2]);
setSportCalorie(Integer.parseInt(info[2]));
i++;
}
} catch (FileNotFoundException e) {
System.out.println("Sport File could not find");
}
} catch (IOException e) {
System.out.println("Sport file could not read!");
}
}
When you only has 3 objects per line, it is actually easier this way.

Related

Difficulty reading .txt data when running Stable Marriage algorithm in Java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am new to Java and I am trying to execute the code below regarding Stable Marrage algorithm, but when executing the code below you get the following error:
Error: For input string: "3 " Exception in thread "main"
java.lang.NullPointerException at
br.com.entrada.GaleShapley.(GaleShapley.java:21) at
br.com.entrada.GaleShapley.main(GaleShapley.java:166)
Gale Shapley Marriage Algorithm
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class GaleShapley
{
private int N, engagedCount;
private String[][] menPref;
private String[][] womenPref;
private String[] men;
private String[] women;
private String[] womenPartner;
private boolean[] menEngaged;
/** Constructor **/
public GaleShapley(String[] m, String[] w, String[][] mp, String[][] wp)
{
N = mp.length;
engagedCount = 0;
men = m;
women = w;
menPref = mp;
womenPref = wp;
menEngaged = new boolean[N];
womenPartner = new String[N];
calcMatches();
}
/** function to calculate all matches **/
private void calcMatches()
{
while (engagedCount < N)
{
int free;
for (free = 0; free < N; free++)
if (!menEngaged[free])
break;
for (int i = 0; i < N && !menEngaged[free]; i++)
{
int index = womenIndexOf(menPref[free][i]);
if (womenPartner[index] == null)
{
womenPartner[index] = men[free];
menEngaged[free] = true;
engagedCount++;
}
else
{
String currentPartner = womenPartner[index];
if (morePreference(currentPartner, men[free], index))
{
womenPartner[index] = men[free];
menEngaged[free] = true;
menEngaged[menIndexOf(currentPartner)] = false;
}
}
}
}
printCouples();
}
/** function to check if women prefers new partner over old assigned partner **/
private boolean morePreference(String curPartner, String newPartner, int index)
{
for (int i = 0; i < N; i++)
{
if (womenPref[index][i].equals(newPartner))
return true;
if (womenPref[index][i].equals(curPartner))
return false;
}
return false;
}
/** get men index **/
private int menIndexOf(String str)
{
for (int i = 0; i < N; i++)
if (men[i].equals(str))
return i;
return -1;
}
/** get women index **/
private int womenIndexOf(String str)
{
for (int i = 0; i < N; i++)
if (women[i].equals(str))
return i;
return -1;
}
/** print couples **/
public void printCouples()
{
System.out.println("Couples are : ");
for (int i = 0; i < N; i++)
{
System.out.println(womenPartner[i] +" "+ women[i]);
}
}
/** main function **/
public static void main(String[] args)
{
System.out.println("Gale Shapley Marriage Algorithm\n");
/** list of men **/
String[] m = {"1", "2", "3"};
/** list of women **/
String[] w = {"1", "2", "3"};
/** men preference **/
String[][] mp = null ;
/** women preference **/
String[][] wp= null ;
// Input.txt is like
// 3 <--defines the size of array
// male preference array
// 1 3 2
// 1 2 3
// 2 3 1
//female preference array
//1 3 2
//2 1 3
//2 1 3
try{
FileInputStream fstream = new FileInputStream("input.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
int line=0;
int k=0;
int n=0;
int i=0;
while ((strLine = br.readLine()) != null) {
if(line==0){
n =Integer.valueOf(strLine);
mp=new String[n][n];
wp=new String[n][n];
line++;
}
else{
String[] preferences=strLine.split(" ");
if(i<n){
mp[i]=preferences;
}
else{
wp[i-n]=preferences;
}
i++;
}
}
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
GaleShapley gs = new GaleShapley(m, w, mp, wp);
}
}
The program is not reading the input.txt input file completely. It is reading only the first line of this file. And I can't solve this. I think the problem should be in the code part below.
while ((strLine = br.readLine()) != null) {
if(line==0){
n =Integer.valueOf(strLine);
mp=new String[n][n];
wp=new String[n][n];
line++;
}
else{
String[] preferences=strLine.split(" ");
if(i<n){
mp[i]=preferences;
}
else{
wp[i-n]=preferences;
}
i++;
}
}
Below is the input file: input.txt
3
male preference array
1 3 2
1 2 3
2 3 1
female preference array
1 3 2
2 1 3
2 1 3
The error is thrown due this : 3 => it contains a whitespace
And when you call the Integer.parse(N), N cannot be parsed to Integer while there's this whitespaces,
To resolve this, i used strLine.trim();
women[i].equals(str) : you are comparing here a string to an Integer is always false and the result of your function womenIndexOf is -1, and this is going to throw an exception of IndexOutOfBounds Exception when using the -1 as index
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class GaleShapley {
private int N, engagedCount;
private String[][] menPref;
private String[][] womenPref;
private String[] men;
private String[] women;
private String[] womenPartner;
private boolean[] menEngaged;
/** Constructor **/
public GaleShapley() {
}
public GaleShapley(String[] m, String[] w, String[][] mp, String[][] wp) {
N = mp.length;
engagedCount = 0;
men = m;
women = w;
menPref = mp;
womenPref = wp;
menEngaged = new boolean[N];
womenPartner = new String[N];
calcMatches();
}
/** function to calculate all matches **/
private void calcMatches() {
while (engagedCount < N) {
int free;
for (free = 0; free < N; free++)
if (!menEngaged[free])
break;
for (int i = 0; i < N && !menEngaged[free]; i++) {
int index = womenIndexOf(menPref[free][i]);
if (womenPartner[index] == null) {
womenPartner[index] = men[free];
menEngaged[free] = true;
engagedCount++;
} else {
String currentPartner = womenPartner[index];
if (morePreference(currentPartner, men[free], index)) {
womenPartner[index] = men[free];
menEngaged[free] = true;
menEngaged[menIndexOf(currentPartner)] = false;
}
engagedCount++;
}
}
}
printCouples();
}
/** function to check if women prefers new partner over old assigned partner **/
private boolean morePreference(String curPartner, String newPartner, int index) {
for (int i = 0; i < N; i++) {
if (womenPref[index][i].equals(newPartner))
return true;
if (womenPref[index][i].equals(curPartner))
return false;
}
return false;
}
/** get men index **/
private int menIndexOf(String str) {
for (int i = 0; i < N; i++)
if (men[i].equals(str))
return i;
return -1;
}
/** get women index **/
private int womenIndexOf(String str) {
for (int i = 0; i < N; i++) {
if (women[i].equals(str))
return i;
}
return -1;
}
/** print couples **/
public void printCouples() {
System.out.println("Couples are : ");
for (int i = 0; i < N; i++) {
System.out.println(womenPartner[i] + " " + women[i]);
}
}
/** main function **/
public static void main(String[] args) {
System.out.println("Gale Shapley Marriage Algorithm\n");
/** list of men **/
String[] m = { "1", "2", "3" };
/** list of women **/
String[] w = { "1", "2", "3" };
/** men preference **/
String[][] mp = null;
/** women preference **/
String[][] wp = null;
try {
FileInputStream fstream = new FileInputStream("C:\\Users\\Youssef\\Projects\\STS\\TEST\\src\\input");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
int line = 0;
int n = 0;
int i = 0;
while ((strLine = br.readLine()) != null) {
if (line == 0) {
n = Integer.valueOf(strLine.trim());
mp = new String[n][n];
wp = new String[n][n];
line++;
} else {
if (strLine != null && !strLine.equals("") && !strLine.contains("male")
&& !strLine.contains("female")) {
String[] preferences = strLine.split(" ");
if (i < n) {
mp[i] = preferences;
} else {
if (i - n < w.length) {
wp[i - n] = preferences;
}
}
i++;
}
}
}
in.close();
new GaleShapley(m, w, mp, wp);
} catch (Exception e) {// Catch exception if any
e.printStackTrace();
System.err.println("Error: " + e.getMessage());
}
}
}
Follows the code running below:
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class GaleShapley
{
private int N, engagedCount;
private String[][] menPref;
private String[][] womenPref;
private String[] men;
private String[] women;
private String[] womenPartner;
private boolean[] menEngaged;
public GaleShapley() {}
/** Constructor **/
public GaleShapley(String[] m, String[] w, String[][] mp, String[][] wp)
{
N = mp.length;
engagedCount = 0;
men = m;
women = w;
menPref = mp;
womenPref = wp;
menEngaged = new boolean[N];
womenPartner = new String[N];
calcMatches();
}
/** function to calculate all matches **/
private void calcMatches()
{
while (engagedCount < N)
{
int free;
for (free = 0; free < N; free++)
if (!menEngaged[free])
break;
for (int i = 0; i < N && !menEngaged[free]; i++)
{
int index = womenIndexOf(menPref[free][i]);
if (womenPartner[index] == null)
{
womenPartner[index] = men[free];
menEngaged[free] = true;
engagedCount++;
}
else
{
String currentPartner = womenPartner[index];
if (morePreference(currentPartner, men[free], index))
{
womenPartner[index] = men[free];
menEngaged[free] = true;
menEngaged[menIndexOf(currentPartner)] = false;
}
}
}
}
printCouples();
}
/** function to check if women prefers new partner over old assigned partner **/
private boolean morePreference(String curPartner, String newPartner, int index)
{
for (int i = 0; i < N; i++)
{
if (womenPref[index][i].equals(newPartner))
return true;
if (womenPref[index][i].equals(curPartner))
return false;
}
return false;
}
/** get men index **/
private int menIndexOf(String str)
{
for (int i = 0; i < N; i++)
if (men[i].equals(str))
return i;
return -1;
}
/** get women index **/
private int womenIndexOf(String str)
{
for (int i = 0; i < N; i++)
if (women[i].equals(str))
return i;
return -1;
}
/** print couples **/
public void printCouples()
{
System.out.println("Couples are : ");
for (int i = 0; i < N; i++)
{
System.out.println(womenPartner[i] +" "+ women[i]);
}
}
/** main function **/
public static void main(String[] args) {
System.out.println("Gale Shapley Marriage Algorithm\n");
/** list of men **/
String[] m = { "1", "2", "3" };
/** list of women **/
String[] w = { "1", "2", "3" };
/** men preference **/
String[][] mp = null;
/** women preference **/
String[][] wp = null;
try {
FileInputStream fstream = new FileInputStream("src\\input.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
int line = 0;
int n = 0;
int i = 0;
while ((strLine = br.readLine()) != null) {
if (line == 0) {
n = Integer.valueOf(strLine.trim());
mp = new String[n][n];
wp = new String[n][n];
line++;
} else {
if (strLine != null && !strLine.equals("") && !strLine.contains("male")
&& !strLine.contains("female")) {
String[] preferences = strLine.split(" ");
if (i < n) {
mp[i] = preferences;
} else {
if (i - n < w.length) {
wp[i - n] = preferences;
}
}
i++;
}
}
}
in.close();
new GaleShapley(m, w, mp, wp);
} catch (Exception e) {// Catch exception if any
e.printStackTrace();
System.err.println("Error: " + e.getMessage());
}
}
}
The result is:
Gale Shapley Marriage Algorithm
Couples are :
1 1
2 2
3 3

My Program stops printing to console, but continues to run in background. No Exception is thrown

My program Runs and prints the first few system.out statements, then stops printing them. There is no exception thrown, and the program continues to run until manually terminated.
I've tried System.out.flush(); but am not even sure where to put that
import java.io.*;
import java.util.ArrayList;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) throws
FileNotFoundException {
String inputFileStr = args[0];//"input.txt";
String outputFileStr = args[1];//"output.txt";
String deleteFileStr = args[2];//"CS401Project5Delete_Varner_Sav58.txt";//
String replaceFileStr = args[3]; //"CS401Project5Replace_VARNER_SAV58.txt";
// create files w/ corresponding file names
try{
File inputFile = new File(inputFileStr);
File outputFile = new File(outputFileStr);
File deleteFile = new File(deleteFileStr);
File replaceFile = new File(replaceFileStr);
// create arrayLists
ArrayList<StringBuilder> deleteArray;
ArrayList<StringBuilder> replaceArray;
ArrayList<StringBuilder> inputArray;
ArrayList<String> inputStringArray = new ArrayList<>();
ArrayList<String> tokensArray = new ArrayList<>();
ArrayList<Integer> frequenciesArray = new ArrayList<>();
// turn Files into arrayLists of StringBuilders
deleteArray = fileToArray(deleteFile);
replaceArray = fileToArray(replaceFile);
inputArray = fileToArray(inputFile);
System.out.println("# words in original file: " + wordCount(inputArray));
// create a deleteList object
DeleteList delete = new DeleteList();
delete.compareArray(inputArray, deleteArray);
System.out.println("Word Count After Deleteing noise: " + delete.wordCount(inputArray));
System.out.flush();
// create a replacelist object
ReplaceList replace = new ReplaceList();
replace.compareArray(inputArray, replaceArray);
System.out.println("Word count after replacing words: " + replace.wordCount(inputArray));
System.out.println("New input printed to 'output.txt'");
}
catch (FileNotFoundException e){
System.out.println("File not found");
}
}
// turns a file into an arraylist of string builders
public static ArrayList<StringBuilder> fileToArray(File fileName) throws FileNotFoundException {
ArrayList<String> array = new ArrayList<>();
ArrayList<StringBuilder> sbArray = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = br.readLine()) != null)
{
if (!line.isEmpty()) {
Stream.of(line.split("\\s+")).forEachOrdered(word -> array.add(word));
}
}
} catch (Exception e) {
System.out.printf("Caught Exception: %s%n", e.getMessage());
e.printStackTrace();
}
for(int i = 0; i < array.size(); i++) {
StringBuilder sb = new StringBuilder();
sb.append(array.get(i));
sbArray.add(sb);
}
for(int i = 0; i < sbArray.size(); i ++) {
if
(sbArray.get(i).toString().endsWith(",") ||
sbArray.get(i).toString().endsWith(".") ||
sbArray.get(i).toString().endsWith(" ")
||sbArray.get(i).toString().endsWith(":")) {
sbArray.get(i).deleteCharAt(array.get(i).length() - 1);
}
}
return sbArray;
}
public static int wordCount(ArrayList<StringBuilder> array) {
int count = 0;
for (int i = 0; i < array.size(); i++) {
count++;
}
return count;
}
}
import java.util.ArrayList;
public class DeleteList extends ArrayList<Object> implements MyInterface {
/**
*
*/
private static final long serialVersionUID = 1L;
//constructor
#Override
public ArrayList<StringBuilder>
compareArray(ArrayList<StringBuilder> inputArray, ArrayList<StringBuilder> deleteArray) {
for (int i = 0; i < deleteArray.size(); i++) {
for (int j = 0; j < inputArray.size(); j++) {
if (deleteArray.get(i).toString().equals(inputArray.get(j).toString())){
inputArray.remove(j);
}
}
}
return inputArray;
}
#Override
public int wordCount(ArrayList<StringBuilder> inputArray) {
int count = 0;
for (int i = 0; i < inputArray.size(); i++) {
count++;
}
return count;
}
}
import java.util.ArrayList;
public class ReplaceList extends ArrayList<Object> implements MyInterface {
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
public ArrayList<StringBuilder>
compareArray(ArrayList<StringBuilder> inputArray, ArrayList<StringBuilder> replaceArray) {
String wordToReplace, wordReplacingWith = null;
for (int i = 0; i < replaceArray.size(); i++) {
wordToReplace = replaceArray.get(i).toString();
wordReplacingWith = replaceArray.get(i +1).toString();
for (int j = 0; j < inputArray.size(); j++) {
if (inputArray.get(j).toString().equalsIgnoreCase((wordToReplace))) {
StringBuilder strB = new StringBuilder();
strB.append(wordReplacingWith);
inputArray.set(j, strB);
}
}
}
return inputArray;
}
#Override
public int wordCount(ArrayList<StringBuilder> inputArray) {
int count = 0;
for (int i = 0; i < inputArray.size(); i++) {
count++;
}
return count;
}
}
It should be printing to the console:
words in the original file :
words after deleting noise:
words after replacing words:
New Input printed to "output.txt" <--- (i haven't coded this part yet)
Note:
I have to use string builders, implement an interface, and have the
delteList and replaceList extend ArrayList & handle all exceptions in
main
You're problem is this:
ReplaceList#compareArray
while (i < replaceArray.size()) {
wordReplacingWith = replaceArray.get(i + 1).toString();
}
You probably want to increment i at some point or more likely you need a different counter here.
And those System.exit() commands that prevent compilation ;)
The only thing I am seeing in the updated version is a potential ArrayIndexOutOfBoundsException for
for (int i = 0; i < replaceArray.size(); i++) {
...
wordReplacingWith = replaceArray.get(i +1).toString();
...
}
Unrelated to any endless loop problem you might still have:
DeleteList#compareArray is likely to skip elements after a remove operation,
as the new element on position j (the former j+1) element is not covered by your loop.

A method calling other method in another class is not working properly

so i have two classes
It's supossed to be like a digital movie shop, so it should return the user names, the movie names and the rating of the movies
This is the interface one:
import modelo.Matriz;
public class MenuConsola {
private Matriz userItem;
public MenuConsola(){
String[] peliculas = { "Toy story2", "Jumanji", "Amelie", "Wolverine", "Spider Man", "Yes Men", "Sabrina",
"Tom and Huck", "Sudden Death", "GoldenEye" };
String[] usuarios = { "Jhon", "Michael", "Jimmy", "Janis", "Carla", "Angie" };
userItem = new Matriz(peliculas, usuarios);
cargarMatriz();
mostrarBanner();
mostrarUsuarios();
System.out.println("\n");
mostrarPeliculas();
//System.out.println(mostrarMatriz());
}
public void cargarMatriz(){
userItem.cargarCalificaciones();
}
public String mostrarMatriz(){
return userItem.mostrarMatriz();
}
static void appendChars(StringBuilder sb, char c, int count) {
for (int i = 0; i < count; i++) {
sb.append(c);
}
}
public void mostrarUsuarios(){
System.out.println("Usuarios:");
String[] usuarios = userItem.obtenerUsuarios();
int c = 1;
for(String us : usuarios){
System.out.println(c + ". " + us + "\t");
c++;
}
}
public void mostrarPeliculas(){
System.out.println("Peliculas:");
String[] pelis = userItem.obtenerPeliculas();
int c = 1;
for(String pel : pelis){
System.out.println(c + ". " + pel + "\t");
c++;
}
}
**public void mostrarMayor(){
System.out.println(userItem.darPeliculaMayorPromedio());
}
public void mostrarMenor(){
System.out.println(userItem.darPeliculaMenorPromedio());
}**
public static void main(String[] args) {
MenuConsola menu = new MenuConsola();
}
}
And this is the matrix one:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Matriz {
private String[] peliculas;
private String[] usuarios;
private int[][] calificaciones;
public Matriz(String[] pelis, String[] users) {
this.peliculas = pelis;
this.usuarios = users;
calificaciones = new int[users.length][pelis.length];
}
public void cargarCalificaciones() {
BufferedReader br;
try {
br = new BufferedReader(new FileReader("data/userItem.txt"));
String linea = "";
int fila = 0;
while ((linea = br.readLine()) != null) {
String[] data = linea.split("\t");
int col = 0;
for (String strRatig : data) {
calificaciones[fila][col] = Integer.parseInt(strRatig);
col++;
}
fila++;
}
br.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
}
}
public String mostrarMatriz(){
String mensaje = "";
for(int i = 0; i<calificaciones.length; i++){
for(int j = 0; j < calificaciones[0].length; j++){
mensaje += " " + calificaciones[i][j];
}
mensaje += "\n";
}
return (mensaje);
}
public String[] obtenerPeliculas() {
return peliculas;
}
*/
public String[] obtenerUsuarios() {
return usuarios;
}
**public String darPeliculaMayorPromedio**(){
int mayor = calificaciones[0][0];
String peliMayor = "";
for ( int i = 0 ; i < calificaciones.length ; i++ )
{
for ( int j = 0 ; j < calificaciones[i].length ; j++ )
{
if ( calificaciones[i][j] > mayor )
{
mayor = calificaciones[i][j];
peliMayor = peliculas[j];
}
}
}
return peliMayor;
}
**public String darPeliculaMenorPromedio(){**
int menor = calificaciones[0][0];
String peliMenor = "";
for ( int i = 0 ; i < calificaciones.length ; i++ )
{
for ( int j = 0 ; j < calificaciones[i].length ; j++ )
{
if ( calificaciones[i][j] < menor )
{
menor = calificaciones[i][j];
peliMenor = peliculas[j];
}
}
}
return peliMenor;
}
}
Ok this is all the code, i don't know why isn't it printing something? isn't the array or matrix initializated? I doesn't give me any error when i compile and it executes normally until the last two methods
I would think its maybe because you haven't initilised your array that your looking through so it would return nothing. Try initialising the array full of values and then you may find you'll get some result
there doesnt seem to be enough code to accurately answer this question.
Stepping through with a debugger is the best bet, but here are some potential failures I can brainstorm
userItem is not static. Since you call userItem.darPeliculaMenorPromedio() in an encapsulated method, you need to either have an instantiated object (which I can see you don't) or the class needs to be static (which I assume it isn't since the methods are not static either) - this should throw an error though, so I assume its not executing.
you never execute the functions mostrarMayor and mostrarMenor. I can;t see your main class, and what calls are in it, but you would need to call and execute the two functions in your main.

How to subtract two string arrays in java as they are shown in code

//What should I do to subtract quan from objIn?
//means quan has values 1,2,7,9 and objIn has values 5,6,7,8 then how to subtract so that result is 4,4,0,1 as i want operation quan[]=quan[]-objIn[] to be done?
public static void Equalizer(int i, int s, String quan[], String objIn[])
{
int j;
Scanner Inp = new Scanner(System.in);
for(j=0;j<i;j++)
{
System.out.print(objIn[j]+"=");
objIn[j]=Inp.nextLine();
}
for(j=0;j<s;j++)
{
System.out.print(quan[j]+"=");
quan[j]=Inp.nextLine();
}
}
There's a subtract() method
public String[] subtract(String[] sa1, String[] sa2){
List<String> r = new ArrayList<>();
for (int i = 0; i < sa1.length; i++){
if (i >= s2.length) {
r.add(sa1[i]);
continue;
}
try {
r.add(String.valueOf(Integer.parseInt(sa1[i]) - Integer.parseInt(sa2[i])));
} catch (ParseException e) {
e.printStackTrace();
}
}
return r.toArray(new String[r.size()]);
}

Java: Printing Arraylist to Output File?

EDIT: To test these cases, change sort and filter methods to the following:
EXAMPLE SORT METHOD:
public void sortTitle() {
Collections.sort(songs2, SongComparator.byTitle()); // now we have a sorted list
}
EXAMPLE FILTER METHOD (FOR STRING INPUT):
public void filterTitle(String s) {
int n = 0;
if (n == 0) {
n++;
for (Song song1 : songs2) {
if ((!(((song1.title).contains(s))))) {
itemsToRemove.add(song1);
}
}
songs2.removeAll(itemsToRemove);
itemsToRemove.clear();
}
}
EXAMPLE FILTER METHOD (FOR INT INPUT):
public void filterRank(Range r) {
int n = 0;
if (n == 0) {
n++;
for (Song song1 : songs2) {
if (song1.rank > (r.getMax()) || (song1.rank) < (r.getMin())) {
itemsToRemove.add(song1);
}
}
songs2.removeAll(itemsToRemove);
itemsToRemove.clear();
}
}
TEST CASES:
Input strings should be like the following examples:
sort:title
This input runs successfully until
the line System.setOut(out); in the main class, where it begins to print spaces and does not successfully print the collection. This may be because of a problem with the toString method in the SongCollection class.
artist:Paramore
or
title:Misery Business
This input runs successfully through the entire program (the program does not terminate because the while loop does not terminate), except instead of printing the collection, a blank space is printed.
ADDITIONAL DETAILS:
This question is a followup to a previous question I asked, since I have short time constraints on this project (it is due tomorrow).
The primary problem I am experiencing with this is that the program is failing to output correctly, even though the methods and code in the main for printing seems logically sound.
Printing arraylist into output file?
For some reason, it takes an extraordinary amount of time for the ArrayLists to be printed to the output file, usually 20-30 minutes. However, this only happens with the sort methods or the filterTitle or filterArtist methods (methods that concern String inputs).
When I run filterRank or filterYear, it runs perfectly fine.
When I print the song2 ArrayList directly from the filter methods, the only thing that is printed is [], which means the ArrayList is empty, but it shouldn't be? And the filterRank and filterYear methods still work regardless of this.
Somehow I think it's related, though.
Input file can be found here: http://staff.rentonschools.us/hhs/ap-comp-science/projects/download/agazillionsongs.txt?id=223098
Full code for compilation:
import java.io.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
import java.util.Comparator;
import java.util.Scanner;
import java.util.StringTokenizer;
public class GazillionSongs {
public static void main(String[] args) throws FileNotFoundException, IOException {
System.out.println("Welcome to Java Song Collection!"); // greets the user
System.out
.println("This program sorts and filters large databases of popular songs."); // explains purpose of program
System.out
.println("This program is able to filter and sort by year, artist, title and rank.");
System.out
.println("Please enter a file that contains a database you wish to filter or sort. (i.e, alistofsongs.txt)"); // sample file = agazillionsongs.txt
Scanner fileInput = new Scanner(System.in); //Scanner which accepts filename
String filename = fileInput.nextLine();
File f = new File(filename); //creates file from input
/*error check for file here*/
Scanner fileScanner = new Scanner(f); //inputs data from file
ArrayList<Song> songs = new ArrayList<Song>();
while ((fileScanner.hasNextLine())) {
songs.add(Song.parse(fileScanner.nextLine()));
}
System.out
.println("Please select which commands you would like to use for the program.");
System.out
.println("Please format your command like the following example: year:<year(s)> rank:<rank(s)> artist:<artist> title:<title> sortBy:<field>");
System.out.println();
System.out.println("You may pick any number of commands you want.");
System.out
.println("For years and rank, you may select a range of years or ranks.");
System.out
.println("For artists and titles, you may enter a partial name or title.");
System.out.println("i.e, year:1983 rank:1");
Scanner input = new Scanner(System.in);
while (input.hasNextLine()) {
int n = 0;
SongCollection collection = new SongCollection(songs);
String inputType = input.nextLine();
String delims = "[ ]";
String[] tokens = inputType.split(delims);
for (int i = 0; i < tokens.length; i++) {
n = 0;
if (n == 0) {
if ((tokens[i]).contains("year:")) {
collection.filterYear(Range.parse(tokens[i]));
n = 1;
}// end of year loop
if ((tokens[i]).contains("rank:")) {
collection.filterRank(Range.parse(tokens[i]));
n = 1;
}// end of rank
if ((tokens[i]).contains("artist:")) {
collection.filterArtist(tokens[i]);
n = 1;
}// end of artist
if ((tokens[i]).contains("title:")) {
collection.filterTitle(tokens[i]);
n = 1;
}// end of title
if ((tokens[i]).contains("sort:")) {
if ((tokens[i]).contains("title")) {
collection.sortTitle();
n = 1;
}// end of sort title
if ((tokens[i]).contains("artist")) {
collection.sortArtist();
n = 1;
}// end of sort artist
if ((tokens[i]).contains("rank")) {
collection.sortRank();
n = 1;
}// end of sort rank
if ((tokens[i]).contains("year")) {
collection.sortYear();
n = 1;
}// end of sort year
}//end of sort
}// end of for loop
}// end of input.hasNextline loop
final PrintStream console = System.out; //saves original System.out
File outputFile = new File("output.txt"); //output file
PrintStream out = new PrintStream(new FileOutputStream(outputFile)); //new FileOutputStream
System.setOut(out); //changes where data will be printed
System.out.println(collection.toString());
System.setOut(console); //changes output to print back to console
Scanner outputFileScanner = new Scanner(outputFile); //inputs data from file
while ((outputFileScanner.hasNextLine())) { //while the file still has data
System.out.println(outputFileScanner.nextLine()); //print
}
outputFileScanner.close();
out.close();
}
}// end of main
}// end of class
class Song{
public enum Order {Year, Rank, Title, Artist}
public int year;
public int rank;
public String artist;
public String title;
public static Song parse(String s) {
Song instance = new Song();
StringTokenizer tokenizer = new StringTokenizer(s, "\t");
instance.year = Integer.parseInt(tokenizer.nextToken());
instance.rank = Integer.parseInt(tokenizer.nextToken());
instance.artist = (tokenizer.nextToken());
instance.title = (tokenizer.nextToken());
return instance;
}
public int getYear() {
return year;
}
public int getRank() {
return rank;
}
public String getArtist() {
return artist;
}
public String getTitle() {
return title;
}
public String toString() {
String output = "\n\nYear = " + year + "\nRank = " + rank + "\nArtist = "
+ artist + "\nTitle = " + title;
return output;
}
}
class Range {
private int min;
private int max;
public Range() {
System.out.println("Please wait.");
}
public static Range parse(String s) {
Range instance = new Range(); // instance is created here so object
// variables may be accessed
String field; // String to contain deleted part of user input
StringTokenizer tokenizer = new StringTokenizer(s, "-");
StringTokenizer tokenizer2 = new StringTokenizer(s, ":");// for separating "field:" from the
// other part of the String
if (s.contains(":")) { // this deletes the "field:" of the user input so
// it does not interfere with the parsing
field = (tokenizer2.nextToken());
s = s.replace(field, "");
s = s.replace(":", "");
}
if (s.contains("-")) {
instance.min = Integer.parseInt(tokenizer.nextToken());
instance.max = Integer.parseInt(tokenizer.nextToken());
} else if (!(s.contains("-"))) {
{
instance.min = Integer.parseInt(s);
instance.max = Integer.parseInt(s);
}
}
System.out.println("Range max = " + instance.max);
System.out.println("Range min = " + instance.min);
return instance;
}
public boolean contains(int n) {
if (n > min && n < max) { //if the number is contained in the range, method returns true.
return true;
} else if (n == min && n == max) {
return true;
} else {
return false;
}
}
public int getMin() {
return min;
}
public int getMax() {
return max;
}
}
class SongCollection {
ArrayList<Song> songs2;
ArrayList<Song> itemsToRemove = new ArrayList<Song>(); // second collection
// for items to
// remove
public SongCollection(ArrayList<Song> songs) { // constructor for SongCollection
System.out.println("Test");
this.songs2 = songs;
}
public void filterYear(Range r) {
int n = 0;
if (n == 0) {
System.out.println("Program is processing.");
n++;
for (Song song1 : songs2) {
if (song1.year > (r.getMax()) || (song1.year) < (r.getMin())) {
itemsToRemove.add(song1);
}
}
songs2.removeAll(itemsToRemove);
itemsToRemove.clear();
}
System.out.println(songs2);
}
public void filterRank(Range r) {
int n = 0;
if (n == 0) {
System.out.println("Program is processing.");
n++;
for (Song song1 : songs2) {
if (song1.rank > (r.getMax()) || (song1.rank) < (r.getMin())) {
itemsToRemove.add(song1);
}
}
songs2.removeAll(itemsToRemove);
itemsToRemove.clear();
}
System.out.println(songs2);
}
public void filterArtist(String s) {
int n = 0;
if (n == 0) {
System.out.println("Program is processing.");
n++;
for (Song song1 : songs2) {
if ((!(((song1.artist).contains(s))))) {
itemsToRemove.add(song1);
}
}
songs2.removeAll(itemsToRemove);
itemsToRemove.clear();
}
System.out.println(songs2);
}
public void filterTitle(String s) {
int n = 0;
if (n == 0) {
System.out.println("Program is processing.");
n++;
for (Song song1 : songs2) {
if ((!(((song1.title).contains(s))))) {
itemsToRemove.add(song1);
}
}
songs2.removeAll(itemsToRemove);
itemsToRemove.clear();
}
System.out.println(songs2);
}
public void sortTitle() {
Collections.sort(songs2, SongComparator.byTitle()); // now we have a sorted list
System.out.println(songs2);
}
public void sortRank() {
Collections.sort(songs2, SongComparator.byRank()); // now we have a sorted list
System.out.println(songs2);
}
public void sortArtist() {
Collections.sort(songs2, SongComparator.byArtist()); // now we have a sorted list
System.out.println(songs2);
}
public void sortYear() {
Collections.sort(songs2, SongComparator.byYear()); // now we have a sorted list
System.out.println(songs2);
}
public String toString() {
String result = "";
for (int i = 0; i < songs2.size(); i++) {
result += " " + songs2.get(i);
}
return result;
}
}
class SongComparator implements Comparator<Song> {
public enum Order{
YEAR_SORT, RANK_SORT, ARTIST_SORT, TITLE_SORT
}
private Order sortingBy;
public SongComparator(Order sortingBy){
this.sortingBy = sortingBy;
}
public static SongComparator byTitle() {
return new SongComparator(SongComparator.Order.TITLE_SORT);
}
public static SongComparator byYear() {
return new SongComparator(SongComparator.Order.YEAR_SORT);
}
public static SongComparator byArtist() {
return new SongComparator(SongComparator.Order.ARTIST_SORT);
}
public static SongComparator byRank() {
return new SongComparator(SongComparator.Order.RANK_SORT);
}
#Override
public int compare(Song song1, Song song2) {
switch (sortingBy) {
case YEAR_SORT:
return Integer.compare(song1.year, song2.year);
case RANK_SORT:
return Integer.compare(song1.rank, song2.rank);
case ARTIST_SORT:
return song1.artist.compareTo(song2.artist);
case TITLE_SORT:
return song1.title.compareTo(song2.title);
}
throw new RuntimeException(
"Practically unreachable code, can't be thrown");
}
}
I tried to run this code and it works fine and fast. I am using file you posted and as you can see, test value for searching is "year:1983 sort:title". I also simplified it by removing while-cycle and user-input filename and filter string, so anyone can easily reproduce it.
If you want to help, I need to know, how to reproduce that 20-30 minute outputing to file.
:
import java.io.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
import java.util.Comparator;
import java.util.Scanner;
import java.util.StringTokenizer;
public class GazillionSongs {
public static void main(String[] args) throws FileNotFoundException, IOException {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to Java Song Collection!"); // greets the user
System.out
.println("This program sorts and filters large databases of popular songs."); // explains purpose of program
System.out
.println("This program is able to filter and sort by year, artist, title and rank.");
System.out
.println("Please enter a file that contains a database you wish to filter or sort. (i.e, alistofsongs.txt)"); // sample file = agazillionsongs.txt
File f = new File("agazillionsongs.txt"); //creates file from input
/*error check for file here*/
Scanner fileScanner = new Scanner(f); //inputs data from file
List<Song> songs = new ArrayList<Song>();
while ((fileScanner.hasNextLine())) {
Song song = Song.parse(fileScanner.nextLine());
songs.add(song);
}
System.out
.println("Please select which commands you would like to use for the program.");
System.out
.println("Please format your command like the following example: year:<year(s)> rank:<rank(s)> artist:<artist> title:<title> sortBy:<field>");
System.out.println();
System.out.println("You may pick any number of commands you want.");
System.out
.println("For years and rank, you may select a range of years or ranks.");
System.out
.println("For artists and titles, you may enter a partial name or title.");
System.out.println("i.e, year:1983 rank:1");
int n = 0;
SongCollection collection = new SongCollection(songs);
String inputType = "year:1983 sort:title";
String delims = "[ ]";
String[] tokens = inputType.split(delims);
for (int i = 0; i < tokens.length; i++) {
n = 0;
if (n == 0) {
if ((tokens[i]).contains("year:")) {
collection.filterYear(Range.parse(tokens[i]));
n = 1;
}// end of year loop
if ((tokens[i]).contains("rank:")) {
collection.filterRank(Range.parse(tokens[i]));
n = 1;
}// end of rank
if ((tokens[i]).contains("artist:")) {
collection.filterArtist(tokens[i]);
n = 1;
}// end of artist
if ((tokens[i]).contains("title:")) {
collection.filterTitle(tokens[i]);
n = 1;
}// end of title
if ((tokens[i]).contains("sort:")) {
if ((tokens[i]).contains("title")) {
collection.sortTitle();
n = 1;
}// end of sort title
if ((tokens[i]).contains("artist")) {
collection.sortArtist();
n = 1;
}// end of sort artist
if ((tokens[i]).contains("rank")) {
collection.sortRank();
n = 1;
}// end of sort rank
if ((tokens[i]).contains("year")) {
collection.sortYear();
n = 1;
}// end of sort year
}//end of sort
}// end of for loop
}// end of input.hasNextline loop
final PrintStream console = System.out; //saves original System.out
File outputFile = new File("output.txt"); //output file
PrintStream out = new PrintStream(new FileOutputStream(outputFile)); //new FileOutputStream
System.setOut(out); //changes where data will be printed
System.out.println(collection.toString());
System.setOut(console); //changes output to print back to console
Scanner outputFileScanner = new Scanner(outputFile); //inputs data from file
while ((outputFileScanner.hasNextLine())) { //while the file still has data
System.out.println(outputFileScanner.nextLine()); //print
}
outputFileScanner.close();
out.close();
}
}// end of main
class Song {
public enum Order {
Year, Rank, Title, Artist
}
public int year;
public int rank;
public String artist;
public String title;
public static Song parse(String s) {
Song instance = new Song();
StringTokenizer tokenizer = new StringTokenizer(s, "\t");
instance.year = Integer.parseInt(tokenizer.nextToken());
instance.rank = Integer.parseInt(tokenizer.nextToken());
instance.artist = (tokenizer.nextToken());
instance.title = (tokenizer.nextToken());
return instance;
}
public int getYear() {
return year;
}
public int getRank() {
return rank;
}
public String getArtist() {
return artist;
}
public String getTitle() {
return title;
}
public String toString() {
String output = "\n\nYear = " + year + "\nRank = " + rank + "\nArtist = "
+ artist + "\nTitle = " + title;
return output;
}
}
class Range {
private int min;
private int max;
public Range() {
System.out.println("Please wait.");
}
public static Range parse(String s) {
Range instance = new Range(); // instance is created here so object
// variables may be accessed
String field; // String to contain deleted part of user input
StringTokenizer tokenizer = new StringTokenizer(s, "-");
StringTokenizer tokenizer2 = new StringTokenizer(s, ":");// for separating "field:" from the
// other part of the String
if (s.contains(":")) { // this deletes the "field:" of the user input so
// it does not interfere with the parsing
field = (tokenizer2.nextToken());
s = s.replace(field, "");
s = s.replace(":", "");
}
if (s.contains("-")) {
instance.min = Integer.parseInt(tokenizer.nextToken());
instance.max = Integer.parseInt(tokenizer.nextToken());
} else if (!(s.contains("-"))) {
{
instance.min = Integer.parseInt(s);
instance.max = Integer.parseInt(s);
}
}
System.out.println("Range max = " + instance.max);
System.out.println("Range min = " + instance.min);
return instance;
}
public boolean contains(int n) {
if (n > min && n < max) { //if the number is contained in the range, method returns true.
return true;
} else if (n == min && n == max) {
return true;
} else {
return false;
}
}
public int getMin() {
return min;
}
public int getMax() {
return max;
}
}
class SongCollection {
List<Song> songs2;
List<Song> itemsToRemove = new ArrayList<Song>(); // second collection
// for items to
// remove
public SongCollection(List<Song> songs) { // constructor for SongCollection
System.out.println("Test");
this.songs2 = songs;
}
public void filterYear(Range r) {
int n = 0;
if (n == 0) {
System.out.println("Program is processing.");
n++;
for (Song song1 : songs2) {
if (song1.year > (r.getMax()) || (song1.year) < (r.getMin())) {
itemsToRemove.add(song1);
}
}
songs2.removeAll(itemsToRemove);
itemsToRemove.clear();
}
System.out.println(songs2);
}
public void filterRank(Range r) {
int n = 0;
if (n == 0) {
System.out.println("Program is processing.");
n++;
for (Song song1 : songs2) {
if (song1.rank > (r.getMax()) || (song1.rank) < (r.getMin())) {
itemsToRemove.add(song1);
}
}
songs2.removeAll(itemsToRemove);
itemsToRemove.clear();
}
System.out.println(songs2);
}
public void filterArtist(String s) {
int n = 0;
if (n == 0) {
System.out.println("Program is processing.");
n++;
for (Song song1 : songs2) {
if ((!(((song1.artist).contains(s))))) {
itemsToRemove.add(song1);
}
}
songs2.removeAll(itemsToRemove);
itemsToRemove.clear();
}
System.out.println(songs2);
}
public void filterTitle(String s) {
int n = 0;
if (n == 0) {
System.out.println("Program is processing.");
n++;
for (Song song1 : songs2) {
if ((!(((song1.title).contains(s))))) {
itemsToRemove.add(song1);
}
}
songs2.removeAll(itemsToRemove);
itemsToRemove.clear();
}
System.out.println(songs2);
}
public void sortTitle() {
Collections.sort(songs2, SongComparator.byTitle()); // now we have a sorted list
System.out.println(songs2);
}
public void sortRank() {
Collections.sort(songs2, SongComparator.byRank()); // now we have a sorted list
System.out.println(songs2);
}
public void sortArtist() {
Collections.sort(songs2, SongComparator.byArtist()); // now we have a sorted list
System.out.println(songs2);
}
public void sortYear() {
Collections.sort(songs2, SongComparator.byYear()); // now we have a sorted list
System.out.println(songs2);
}
public String toString() {
String result = "";
for (int i = 0; i < songs2.size(); i++) {
result += " " + songs2.get(i);
}
return result;
}
}
class SongComparator implements Comparator<Song> {
public enum Order {
YEAR_SORT, RANK_SORT, ARTIST_SORT, TITLE_SORT
}
private Order sortingBy;
public SongComparator(Order sortingBy) {
this.sortingBy = sortingBy;
}
public static SongComparator byTitle() {
return new SongComparator(SongComparator.Order.TITLE_SORT);
}
public static SongComparator byYear() {
return new SongComparator(SongComparator.Order.YEAR_SORT);
}
public static SongComparator byArtist() {
return new SongComparator(SongComparator.Order.ARTIST_SORT);
}
public static SongComparator byRank() {
return new SongComparator(SongComparator.Order.RANK_SORT);
}
#Override
public int compare(Song song1, Song song2) {
switch (sortingBy) {
case YEAR_SORT:
return Integer.compare(song1.year, song2.year);
case RANK_SORT:
return Integer.compare(song1.rank, song2.rank);
case ARTIST_SORT:
return song1.artist.compareTo(song2.artist);
case TITLE_SORT:
return song1.title.compareTo(song2.title);
}
throw new RuntimeException(
"Practically unreachable code, can't be thrown");
}
}
EDIT :
Question:
title:Misery Business
This input runs successfully through the entire program (the program does not terminate because the while loop does not terminate), except instead of printing the collection, a blank space is printed.
Yes, because in your method, you are testing, if it contains title:Misery Business not Misery Business.
First of all, you cant use that tokenizer for anything, that contains space. But for one-word only, you can change it as following :
Tested and working for title:Misery :
public void filterTitle(String s) {
int n = 0;
s = s.split(":")[1];
if (n == 0) {
System.out.println("Program is processing.");
n++;
for (Song song1 : songs2) {
if (song1.title.contains(s) == false) {
itemsToRemove.add(song1);
}
}
songs2.removeAll(itemsToRemove);
itemsToRemove.clear();
}
System.out.println(songs2);
}

Categories

Resources