How to do I print an arraylist to a JTextArea? - java

I can't seem to figure out how to print an arrayList<String> to a JTextArea and have tried using both append() and setText(). I have also tried to create a method which prints out the ArrayList through a loop, but it can't be added to the JTextArea because it is not of type String.
An applicant is supposed to take a student profile (name, grade, university selections) and add it to the ArrayList<String> Applicants. This is done through a JButton if it holds true for the following if statement:
if (studentsAverage > 74 && validInput && studentsAverage < 100) {
studentChoices.addAll(uniOptions.getSelectedValuesList());
person = new Student (namePromptTF.getText(), averagePromptTF.getText(),Applicants, studentChoices);
arrayCount++;
numberOfApplicants.setText(arrayCount +"/" +100+"students");
person.printProfile(); //dont need
person.studentProfileSort(); // dont need
displayAllApplicants.append(person.returnProfile());
Applicants.add(person);
The array is passed to a Student object that holds:
private ArrayList<Student> ApplicantArray;
ApplicantArray is then sorted through this method:
void studentProfileSort() {
Student profileLine = null;
int numberOfStudents = ApplicantArray.size();
ArrayList<Student> displayAllSorted = new ArrayList<Student>();
for(int i = 1; i<numberOfStudents - 1; i++){
for(int j = 0; j<(numberOfStudents - i); j++) {
if(ApplicantArray.get(i).getFamilyName().compareTo(ApplicantArray.get(i).getFamilyName())>0){
ApplicantArray.set(j, ApplicantArray.get(i));
}
}
ApplicantArray.get(i).returnProfile();
}
}
Is there a way to have a return statement inside of a loop so that I can change my method to a String type?

At first your sorting algorithm does not seem to work
ApplicantArray.get(i).getFamilyName().compareTo(ApplicantArray.get(i).getFamilyName())
You compare the value with it self and this results always in 0. Even if this would work, in the next line you override the array by setting a value rather than swapping the two values or setting to a new ArrayList.
But if everything works, this is how you could print those students:
StringBuilder b = new StringBuilder();
for (Student student : applicantArray) {
b.append(student + "\n"); // this if you implemented toString() in Student
b.append(student.getFamilyName() + ' ' + student.getFirstName() + "\n"); // or something like this
}
textArea.setText(b.toString());
P.S.: you should never use UpperCamelCase for variables or parameters, use lowerCamelCase instead (e.g. ApplicantArray -> applicantArray)

Related

Updating A node in LinkedList by passing a String

I am currently trying to search through a linked list and update the data in a certain node given a String name. I don understand where I am going wrong. I do not receive any error when I run the program but the data that I "update" never changes.
My updateGpa method in my linkedlist class
public void updateGpa(String name, double gpa){
Node<Student> temp = head;
double foundData;
boolean exists = false;
for(int i = 0; (i < size) && !exists; i++){
if(temp.data.getName().equals(name)){
foundData =gpa;
temp.data.setGpa(foundData);
exists = true;
}
temp = getNode(i);
}
}
My main method where I call the updateGpa method
System.out.println("Update a students GPA by entering their name: ");
student = in2.next();
System.out.println("Enter " + student + "'s new GPA: ");
gpa = in1.nextDouble();
studentList.updateGpa(student, gpa);
break;
Student list is my linked list.
I have solved my own problem, unfortunately I have to chalk it up to user error in my main method I have student = in2.next where it should have been in2.nextLine It was only reading in the first name rather than the first and last name so when it was comparing the string in the updateGpa method it would never find a match because the string wasn't exactly equal. Sorry to waste your time but thank you for your input

Can I get subclass variables from array of superclass objects?

First of all, thanks for reading!
I made a class "Sportsman" that is the Superclass of "Footballer".
So I made an array of Sportsman-objects that also contains Footballer objects, no problems here (I have a pretty good idea of how inheritance works).
I can set Footballer-specific variables to the objects in the array, but when I want to print the variables I've just declared to the object i can't call get-methods because the array is a Sportsman-array and not a Footballer-array.
So here is my question: How do i print the Footballer specific variables from a Sportsman Superclass array?
Things to know:
I can't make a separate array for the subclass objects. They must be mixed!
While putting a subclass object in the arrays of superclass objects, I explicitly make it a subclass object. However, I'm not able to use subclass methods on it.
main code:
public class SportApp {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Sportsman[] sportArr = new Sportsman[10];
for(int count=0 ; count < sportArr.length ; count++)
{ System.out.println("Is the sportsman a footballer?");
String answer = input.nextLine();
System.out.println("Last name?");
String lastName = input.nextLine();
System.out.println("name?");
String name = input.nextLine();
switch (answer){
case "yes": System.out.println("Which club does he play in?");
String club = input.nextLine();
System.out.println("At what position?");
String pos = invoer.nextLine();
sportArr[count]=new Footballer(lastName,name,club,pos);
break;
default: System.out.println("What sport?");
String sport = input.nextLine();
sportArr[count]=new Sportsman(lastName,name,sport);
}
}
System.out.println("All sportsmen that don't play football:");
for(int count=0 ; count < sportArr.length ; count++)
{ if(!(sportArr[count] instanceof Footballer))
{ System.out.print("name: ");
sportArr[count].print();} }
System.out.println("All football players sorted by position:");
//Same as previous print, but with added player position and club!
for(int count=0 ; count < sportArr.length ; count++)
{ if(sportArr[count] instanceof Footballer)
{
/*what I've tried:
*System.out.println("front players:");
*if(sportArr[count].getPos()=="front") //the .getPos doesn't work because it wants to invoke it on a Sportsman where getPos doesn't exist
*{ sportArr[count].print();} //as the problem above, it doesn't see the object is also a Footballer so it does the Sportsman print()
*
*I wanted to do a regular sportArr[count].pos to print the Position but even now it doesn't recognise the object as Footballer, so I can't see pos.
*/
}
}}}
You've done a type check with instanceof in the loop, and if it succeeds, you know that you have a Footballer. So, now you have to cast the object to get the correct type:
if(sportArr[count] instanceof Footballer)
{
Footballer fb = (Footballer) sportArr[count];
// Now this should work (note the use of fb, and not using `==` with string literals):
if(fb.getPos().equals("front")) {
// etc..
}
}

How to loop through an array and check for duplicates?

I am creating a program that lets you store 10 items in an array. What I haven't been able to get the program to do is give an error if one of the entered items already exists in the array.
So, for example, if the array looks like [banana, potato, 3, 4, yes, ...] and I enter banana again, it should say "Item has already been stored" and ask me to re-enter the value. The code I currently have is:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int stringNumber = 0;
String[] stringArray = new String[10];
for (int i = 0; i <= stringArray.length; i++) {
out.println("\nEnter a string");
String input = keyboard.next();
stringArray[stringNumber] = input;
out.println("\"" + stringArray[stringNumber] + "\"" + " has been stored.");
PrintArray(stringArray);
stringNumber++;
You can use nested loops to go through the array to see if the new input exists. It would be better to do this in a function. Also when doing this you need to make sure that you are not at the first element or you will get a null pointer exception.
for (int i = 0; i <= stringArray.length; i++) {
boolean isInArray = false;
System.out.println("\nEnter a string");
String input = keyboard.next();
if (i > 0) {
for (int j = 0; j < stringArray.length; j++) {
if (stringArray[j].equalsIgnoreCase(input)) {
isInArray = true;
break;
}
}
}
if (!isInArray) {
stringArray[stringNumber] = input;
} else {
System.out.println("\"" + stringArray[stringNumber-1] + "\""
+ " has been stored.");
}
PrintArray(stringArray);
stringNumber++;
}
It's always better to use a HashSet when you don't want to store duplicates. Then use HashSet#contains() method to check if element is already there. If ordering is important, then use LinkedHashSet.
If you really want to use an array, you can write a utility method contains() for an array. Pass the array, and the value to search for.
public static boolean contains(String[] array, String value) {
// Iterate over the array using for loop
// For each string, check if it equals to value.
// Return true, if it is equal, else continue iteration
// After the iteration ends, directly return false.
}
For iterating over the array, check enhanced for statement.
For comparing String, use String#equals(Object) method.
When you got the String input, you can create a method that will :
Go through the entire array and check if the string is in it (you can use equals() to check content of Strings)
Returns a boolean value wheter the string is in the array or not
Then just add a while structure to re-ask for an input
Basically it can look like this :
String input = "";
do {
input = keyboard.next();
}while(!checkString(input))
The checkString method will just go through all the array(using a for loop as you did to add elements) and returns the appropriate boolean value.
Without introducing some order in your array and without using an addition structure for instance HashSet, you will have to look through the whole array and compare the new item to each of the items already present in the array.
For me the best solution is to have a helper HashSet to check the item for presence.
Also have a look at this question.
To avoid you should use an Set instead of an array and loop until size = 10.
If you need to keep an array, you can use the .contains() method to check if the item is already present in the array.
while (no input or duplicated){
ask for a new string
if (not duplicated) {
store the string in the array
break;
}
}
You should check the input value in array before inserting into it. You can write a method like exists which accepts String[] & String as input parameter, and find the string into the String array, if it finds the result then return true else false.
public boolean exists(String[] strs, String search){
for(String str : strs){
if(str.equals(search))
return true;
}
return false;
}
performance would be O(n) as it searchs linearly.

How to compare against a null element in an array in java?

I have a program where I need to store the results in an arraylist:-
public class ReseedingDBRandomElements {
public static void main(String[] args){
try {
// getting the field Keyword from the csv
String csvfile="/Users/dray/Downloads/ReseedingDBRandomKeywords.csv";
BufferedReader br =new BufferedReader(new FileReader(csvfile));
StringTokenizer st = null;
String line="";
int linenumber=0;
int columnnumber;
// initializing the parameter for each column
int free = 0;
int free1 = 0;
// create the ArrayList
ArrayList<String> Keyword = new ArrayList<String>();
ArrayList<String> Alternate = new ArrayList<String>();
// reading through the csv file
while((line=br.readLine())!=null){
linenumber++;
columnnumber = 0;
st = new StringTokenizer(line,",");
while(st.hasMoreTokens()){
columnnumber++;
String token = st.nextToken();
if("Keyword".equals(token)){
free=columnnumber;
System.out.println("The value of free :"+free);
}else if ("Alternate".equals(token)){
free1=columnnumber;
System.out.println("The value of free1 :"+free1);
}
if(linenumber>1){
if (columnnumber==free)
{
Keyword.add(token);
}else if (columnnumber==free1){
Alternate.add(token);
}
}
}
}
// converting the keyword ArrayList to an array
String[] keyword = Keyword.toArray(new String[Keyword.size()]);
for(int i=0;i<keyword.length;i++){
System.out.println(" The value of the keyword is :"+keyword[i]);
}
// converting the alternate ArrayList to an array
String[] alternate = Alternate.toArray(new String[Alternate.size()]);
for(int i=0;i<alternate.length;i++){
System.out.println("The value of the alternate is :"+alternate[i]);
}
ArrayList<String> AlternateNew = new ArrayList<String>();
for(int i=1;i<keyword.length;i++){
if(keyword[i].equals(keyword[i-1])){
AlternateNew.add(alternate[i-1]);
}else if(!(keyword[i]==(keyword[i-1]))){
AlternateNew.add(alternate[i]);
}
}
String[] alternatenew = AlternateNew.toArray(new String[AlternateNew.size()]);
System.out.println("The length of the array is :"+alternatenew.length);
for(int i=0;i<alternatenew.length;i++){
System.out.println("the value of the alternatenew :"+alternatenew[i]);
}
}catch (Exception e){
System.out.println("there is an error :"+e);
}
}
}
The following is the csv file
Keyword,Alternate
ego kit,baby doll
ego kit,garage park
ego kit,random beats
galaxy tab,venus
galaxy tab,earth
galaxy tab,sun
What I am trying to do is compare elements and store it in an arraylist and display the results, but when last element is getting compared i.e 'galaxy tab' is getting compared to an empty field after last 'galaxy tab', it is not storing the previous result in the arraylist which is 'sun'
The following is the result of the program :
The value of the alternate is :baby doll
The value of the alternate is :garage park
The value of the alternate is :random beats
The value of the alternate is :venus
The value of the alternate is :earth
The last element is not getting stored in the arraylist.
Do not understand why? New to Java programming.
This section has a few problems also present throughout
AlternateNew.add(alternate[0]);
for(int i=1;i<keyword.length;i++){
if(keyword[i]==(keyword[i-1])){
AlternateNew.add(alternate[i]);
}else if(!(keyword[i]==(keyword[i-1]))){
AlternateNew.add(alternate[i]);
}
}
The naming convention in Java is to start with a lowercase letter for a variable name (unless it is a constant), which is why object AlternateNew is highlighted as if it were a class name.
The else if block tests the opposite of the same condition as its if. You could comment out if(!(keyword[i]==(keyword[i-1])), delete, or replace it with a more readable reminder comment, and the result would be the same.
AlternateNew.add(alternate[i]); happens regardless of this condition, in either branch of the if, so either remove the if statement entirely or fix some typo.
As for your actual [edit: original] question, I can't find anything wrong. Are you sure you didn't forget to save the csv file? I ran it using a text file and got output contrary to your post!

To know a class by entering an array value

I have got one string array each in 2 different classes in java.
When I enter a value from any of the arrays, I want to get the class to which that array value belongs.
So how do I get to know the class just by entering an array value?
eg:
import java.io.*;
class Car {
public static void main(String args[]) throws Exception {
System.out.println("The parts of a car are as follows");
for (int i = 1; i <= 5; i++) {
System.out.println(i + str[i]);
}
for (int j = 1; j <= 5; j++) {
System.out.println(j + ch[j]);
}
DataInputStream dis = new DataInputStream(System.in);
System.out.println("Choose and enter any part name to group it under following categories:" + "\n" + "Engine" + "\t" + "\t" + "Bonet");
String part = dis.readLine();
if (part == ch[]) {
System.out.println("Your choosen part is " + part + " and it comes under Engine category");
} else {
System.out.println("Your choosen part is " + part + " and it comes under Bonet category");
}
}
}
class Engine {
String ch[] = {"asd", "fgh"};
}
class Bonet {
String str[] = {"qwe", "rty"};
}
now when a user enters asd i want to display to which class it belongs
I wont give you full code because I believe that creating it yourself will be better for you. Instead here are few facts that you need to take into consideration:
To have access to array stored in other class you would aether have to create instance of that class
Engine engine = new Engine();
engine.ch[0];
or in your case you should probably make your array static
class Engine {
static String ch[] = { "asd", "fgh" };
}
and access it via class name Engine.ch[0]
Arrays are indexed from 0 to arraySize-1
To get size of array you can use its filed length and later use it like
for(int i=0; i<Bonet.str.length; i++){
System.out.println(i+Bonet.str[i]);
}
readLine() from DataInputStream is depracated. Instead you can use nextLine from java.util.Scanner
Scanner scanner = new Scanner(System.in);
//...
String part = scanner.nextLine();
To check if some object is stored in array you will have to iterate over all elements of that array and compare them with your object. Also remember that to compare String objects you should use equals method like part.equals(otherString).
But to make it with less code you can wrap your array into List and use its contains(Object o) method. To wrap array into list you can use asList method from java.util.Arrays class.
if(Arrays.asList(Engine.ch).contains(part)){...
Bare minimum changes to get this to work are as below. Key points:
the contents of Engine and bonet belong to instances of those classes not to car
arrays of size 5 have indicies 0,1,2,3,4, not 1,2,3,4,5
Where going through an array in a loop do not hard code the array size, use .length instead
import java.io.*;
public class Car {
public static void main(String args[]) throws Exception {
System.out.println("The parts of a car are as follows");
Engine engine=new Engine(); //we must create any components we have
Bonet bonet=new Bonet(); //we must create any components we have
for (int i = 0; i <bonet.str.length; i++) {
System.out.println(i +":"+ bonet.str[i]);
}
for (int j = 0; j < engine.ch.length; j++) {
System.out.println(j +":"+ engine.ch[j]);
}
DataInputStream dis = new DataInputStream(System.in);
System.out.println("Choose and enter any part name to group it under following categories:" + "\n" + "Engine" + "\t" + "\t" + "Bonet");
String part = dis.readLine();
boolean isInEngine=false; //assume isn't in engine, try to prove otherwise
for(int i=0;i<engine.ch.length;i++){
if (engine.ch[i].equals(part)){
isInEngine=true;
}
}
if (isInEngine==true) {
System.out.println("Your choosen part is " + part + " and it comes under Engine category");
} else {
System.out.println("Your choosen part is " + part + " and it comes under Bonet category");
}
}
}
class Engine {
String ch[] = {"asd", "fgh"};
}
class Bonet {
String str[] = {"qwe", "rty"};
}
Note; this is far from an optimal solution, ideas to consider:
It is bad practice to refer to the insides of annother class like this, it would be better for each class (engine and bonnet) to include a method .testPart(String string) that would return a boolean as to if it contains the part
The code assumes that if its not in engine it must be in bonet, what if the user enters something crazy
An array list (rather than an array) would allow us to use .contains(String string) rather than using a loop to look though the array
The DataInputStream is no longer supported (note that it appears with a strike through in most IDEs), consider using Scanner scanner = new Scanner(System.in); and then use scanner.nextLine(); to get the line
What if you add a third type of component, better to hold all your parts in an array, then you can easily add annother. An interface (or abstract base class) would promise that all the array contents held the .testPart(String string) and a getName() method; the array/arraylist would be declared as containing the interface/abstract-base-class
You never actually create an instance of Car, which you would do by Car car=new Car();, the Car class could then have methods like car.printOptions(); and car.testComponent(String testString);. The way you're doing it (one long main function) will work fine for small programs, but the bigger your program becomes the harder it will be to work like this. In this case the engine and bonet would be fields of the car class (which logically makes a lot more sense than them just 'hanging around')

Categories

Resources