Object information does not coincide with Array of Object's index - java

I'm trying to get the function infoEst() to iterate over an array of objects
and print out the object's name and location. It iterates fine but it seems like every
index in the array is the exact same as the last entry.
Am I creating the array of objects incorrectly?
import java.util.Scanner;
public class Estudiante {
static String nombre= "", promedio = "", pueblo = "", entrada = "";
static int edad;
static Estudiante[] objArray = new Estudiante[4];
static Scanner input = new Scanner(System.in);
Estudiante(String nom, int ed, String prom, String pueb) {
this.nombre = nom;
this.edad = ed;
this.promedio = prom;
this.pueblo = pueb;
}
static void infoEst(String n) {
for (int i = 0; i < objArray.length; i++) {
if (objArray[i].nombre == n) {
System.out.println(objArray[i].nombre + ", " + objArray[i].pueblo);
}
}
}
public static void main(String[] args) {
objArray[0] = new Estudiante("Joshua", 20, "A", "Aguadilla");
objArray[1] = new Estudiante("Liliana", 21, "A", "Isabella");
objArray[2] = new Estudiante("Cano", 27, "C", "Aguadilla");
objArray[3] = new Estudiante("Eribelto", 22, "F", "Moca");
// does not print anything when executed.
infoEst("Joshua");
infoEst("Liliana");
// the if statement block executes on index 0 so
// it prints Eribelto, Moca 4 times.
infoEst("Eribelto");
// All of these print "Eribelto" which is last in the array
System.out.println(objArray[0].nombre);
System.out.println(objArray[1].nombre);
System.out.println(objArray[2].nombre);
System.out.println(objArray[3].nombre);
}
}

It iterates fine but it seems like every index in the array is the exact same as the last entry.
static String nombre= "", promedio = "", pueblo = "", entrada = "";
Don't use static variables. This means each instance of the class shares the same information.

Related

How do I return string array and string to the array of multispell?

Using the main below, create the methods that will give the String[] result.
Please write the loop in the main to print the array of a multi spell.
public static void main(String[] args) {
// Create array here
// use your array to create new array here
String[] multispell = Attack(“your array”, “ball”);
Output:
Cast Fire ball!!!
Cast Ice ball!!!
Cast Earth ball!!!
Cast Lightning ball!!!
Cast Wind ball!!
my program:
public class Paper {
public static void main (String args[]) {
String[] kind = new String[5];
String [] multispell = Attack4 ( kind , "ball" );
for (int i = 0 ; i< multispell.length ; i++) {
System.out.println ("Cast " + multispell[i]+ "!!!");
}
}
public static String[] Attack4() {
String [] kind111 = {"Fire", "Ice", "Earth", "Lightning", "Wind"};
return kind111 ;
}
}
Is this what you are looking for?
public static void main(String[] args) {
String[] kind = new String[] {
"Fire", "Ice", "Earth", "Lightning", "Wind"
};
String[] multispell = Attack(kind, "ball");
for (int i = 0; i < multispell.length; i++) {
System.out.println("Cast " + multispell[i] + "!!!");
}
}
public static String[] Attack(String[] orig, String attach) {
String[] result = new String[orig.length];
for (int i = 0; i < orig.length; i++) {
result[i] = orig[i] + " " + attach;
}
return result;
}

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;
}
}

How to add items to a list of lists

I aim to print a list of lists containing entry and exit times in the 24 hour decimal format from the "AM"-"PM" String format input by the user as a String array like this:
{6AM#8AM, 11AM#1PM, 7AM#8PM, 7AM#8AM, 10AM#12PM, 12PM#4PM, 1PM#4PM, 8AM#9AM}
I declared the individual lists inside the for loop and assigned them values inside the loop but got the following run time exception from my code:
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
Kindly help me debug my code:
import java.util.*;
public class TimeSchedule
{
public static List<List<Integer>> Timein24hourFormat(String[] input1)
{
List<List<Integer>> scheduledTime = new ArrayList<List<Integer>>();
int [] exitTime = new int[input1.length];
int [] entryTime = new int[input1.length];
for (int i=0;i<input1.length;i++)
{
List<String> listOfStrings = new ArrayList<>();
List<Integer> tempList = scheduledTime.get(i);
String[] timeSlot = input1[i].split("#");
for (int m=0;m<2;m++)
{
listOfStrings.add(timeSlot[m]);
if (listOfStrings.contains("AM"))
{
listOfStrings.remove("AM");
tempList.add(Integer.parseInt(listOfStrings.get(m)));
}
if (listOfStrings.contains("PM") && timeSlot[m].contains("12"))
{
listOfStrings.remove("PM");
tempList.add(Integer.parseInt(listOfStrings.get(m)));
}
if (listOfStrings.contains("PM") && !timeSlot[m].contains("12"))
{
listOfStrings.remove("PM");
tempList.add((Integer.parseInt(listOfStrings.get(m))) + 12);
}
}
}
return scheduledTime;
}
public static void main (String[]args)
{
Scanner input = new Scanner(System.in);
int customersNumber = input.nextInt();
input.nextLine();
String [] entryExitTime = new String[customersNumber];
for (int i=0;i<customersNumber;i++)
{
entryExitTime[i] = input.nextLine();
}
System.out.println(Timein24hourFormat(entryExitTime));
}
}
public static List<List<Integer>> Timein24hourFormat(String[] input1)
{
List<List<Integer>> scheduledTime = new ArrayList<List<Integer>>();
int [] exitTime = new int[input1.length];
int [] entryTime = new int[input1.length];
for (int i=0;i<input1.length;i++)
{
List<String> listOfStrings = new ArrayList<>();
List<Integer> tempList = scheduledTime.get(i);
String[] timeSlot = input1[i].split("#");
scheduledTime is empty at this stage and that's why you can not retrieve value and you get IndexOutOfBoundsException

Writing a random sentence generator in Java

I am trying to create a program that generates random sentences in English (according to general English syntax rules).
I keep getting a bug with my subroutine randomSentence(). What have I missed? Also any suggestions on how I can simplify everything?
The error I am receiving is:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method print(boolean) in the type PrintStream is not applicable for the arguments (void)
at SentenceGenerator.randomSentence(SentenceGenerator.java:80)
at SentenceGenerator.main(SentenceGenerator.java:86)
Code:
import java.util.ArrayList;
import java.util.Random;
public class SentenceGenerator {
private StringData[] stringData;
// An array containing all of the possible words. This is a nested class.
/**
* An object of this type holds the word that will be randomly chosen and printed
*/
public class StringData {
String[] conjunction = {"and", "or", "but", "because"};
String[] proper_noun = {"red", "Jane", "Richard Nixon", "Miss America"};
String[] common_noun = {"man", "woman", "fish", "elephant", "unicorn"};
String[] determiner = {"a", "the", "every", "some"};
String[] adjective = {"big", "tiny", "pretty", "bald"};
String[] intransitive_verb = {"runs", "jumps", "talks", "sleeps"};
String[] transitive_verb = {"loves", "hates", "sees", "knows", "looks for", "finds"};
//find out how many words there are in each list
int conjunctionLength = conjunction.length;
int proper_nounLength = proper_noun.length;
int common_nounLength = common_noun.length;
int determinerLength = determiner.length;
int adjectiveLength = adjective.length;
int intransitive_verbLength = intransitive_verb.length;
int transitive_verbLength = transitive_verb.length;
//Generate random numbers
int rand1 = (int) (Math.random()*conjunctionLength);
int rand2 = (int) (Math.random()*proper_nounLength);
int rand3 = (int) (Math.random()*common_nounLength);
int rand4 = (int) (Math.random()*determinerLength);
int rand5 = (int) (Math.random()*adjectiveLength);
int rand6 = (int) (Math.random()*intransitive_verbLength);
int rand7 = (int) (Math.random()*transitive_verbLength);
String word1 = conjunction[rand1];
String word2 = proper_noun[rand2];
String word3 = common_noun[rand3];
String word4 = determiner[rand4];
String word5 = adjective[rand5];
String word6 = intransitive_verb[rand6];
String word7 = transitive_verb[rand7];
}
static void Sentence() {
String sentence() = SimpleSentence();
}
/**
* subroutine that defines how SimpleSentence is put together, nesting NounPhrase and VerbPhrase subroutines
*/
public static String SimpleSentence() {
String simple_sentence = NounPhrase() + VerbPhrase();
return "";
}
/**
* subroutine that defines the nested variable NounPhrase
*/
public static String NounPhrase() {
String noun_phrase = proper_noun[word2], determiner[word4], common_noun[word3];
return "";
}
/**
* subroutine that defines the nested variable VerbPhrase
*/
static void VerbPhrase() {
String verb_phrase = intransitive_verb[word6], transitive_verb[word7], NounPhrase();
}
/**
* Final subroutine that prints out the random sentence
*/
public static void randomSentence() {
System.out.print(randomSentence());
}
public static void main(String[] args) {
while (true) {
randomSentence();
System.out.println(".\n\n");
try {
Thread.sleep(3000);
}
catch (InterruptedException e) {}
}
}
}
This is the most evident error:
public static void randomSentence() {
System.out.print(randomSentence());
}
You call the method recursively.
Furthermore, the program is full of conceptual errors, you need to study the OO programming paradigm better.
Ok. The first issue :
System.out.print(randomSentence());
randomSentence() returns void, So basically there is nothing for print() to print.
Next --> even if you happen to fix this issue. You are calling randomSentence() recursively and you will get a StackOverflowError. Kindly check your design / code.

calculating the final length

The following code separates the duplicate names into 1 column and sum of numbers associated with the names into the second column.
Like :
Nokia 21
Blackberry 3
Nimbus 30
from the array given in the program.
I want to know the final length of the array that contain these entries. In this case 3. How do i calculate that ?
package keylogger;
import java.util.ArrayList;
import java.util.List;
public class ArrayTester {
private static int finalLength = 0;
private static String Name[][];
private static String data[][] = {
{"Nokia" , "7"},
{"Blackberry" ,"1"},
{"Nimbus","10"},
{"Nokia" , "7"},
{"Blackberry" , "1"},
{"Nimbus","10"},
{"Nokia" , "7"},
{"Blackberry" , "1"},
{"Nimbus","10"}
};
public void calculator() {
Name = new String[data.length][2];
List<String> marked = new ArrayList<String>();
try {
for(int i=0;i<data.length;i++) {
Name[i][0] = data[i][0];
Name[i][1] = data[i][1];
String name = data[i][0];
if(marked.contains(name)) {
continue;
}
marked.add(name);
int k = i + 1;
int v = k;
for (int j = 0; j < data.length - v; j++) {
String s = data[k][0];
if(Name[i][0].equalsIgnoreCase(s)) {
Name[i][0] = s;
Integer z = Integer.parseInt(Name[i][1]) + Integer.parseInt(data[k][1]);
Name[i][1] = z.toString();
}
k++;
}
}
}catch(Exception exc) {
exc.printStackTrace();
}
}
public static void main(String args[]) {
ArrayTester o = new ArrayTester();
o.calculator();
for(String s[] : Name) {
for(String x : s) {
System.out.println(x);
}
}
}
}
As usual, the "problem" is poor coding. Your entire program, properly written, can be reduced to just 3 lines of code (5 if you include defining the array and printing the output):
public static void main(String[] args) {
String data[][] = {{"Nokia", "7"}, {"Blackberry", "1"}, {"Nimbus", "10"},
{"Nokia", "7"}, {"Blackberry", "1"}, {"Nimbus", "10"}, {"Nokia", "7"},
{"Blackberry", "1"}, {"Nimbus", "10"}, {"Zebra", "78"}};
HashMap<String, Integer> totals = new HashMap<String, Integer>();
for (String[] datum : data)
totals.put(datum[0], new Integer(datum[1]) + (totals.containsKey(datum[0]) ? totals.get(datum[0]) : 0));
System.out.println("There are " + totals.size() + " brands: " + totals);
}
Output:
There are 4 brands: {Nimbus=30, Zebra=78, Nokia=21, Blackberry=3}
You can't know it a priori, the size will be known just when you'll have finished splitting the strings and doing your math.
In your example in the end marked.size() will have the size you are looking for but I'd suggest you to directly use a HashMap so that you won't care about searching for existing elements in linear time and then convert it to an array.
Something like:
String[][] names = new String[map.size()];
Set<String> keys = map.keys();
int c = 0;
for (String k : keys)
{
names[c] = new String[2];
names[c][0] = k;
names[c++][1] = map.get(k).toString();
}
As far as I understand it, you want to know the number of distinct names in your array without calling calculator(), right? I don't really know if that makes sense as you still have to go through every entry and compare it with a set. But you could do it with a Set:
private int getNumberOfEntries(String[][] data) {
Set<String> names = new HashSet<String>();
for (int i=0; i<data.length; i++) {
names.add(data[i][1]);
}
return names.size();
}
Now you can just call int n = getNumberOfEntries(data);...
EDIT: Of course it makes more sense to do the sums in the same step, see Bohemians solution for that.

Categories