I am trying to use a 2D array to create JTable. When assigning the values for the columns in the JTable I get the Java.lang.String found error. The data type of the variables are also String and the 2D array is also of type String.
import java.io.*;
import java.util.*;
/**
* Write a description of class PhoneBook here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class PhoneBook
{
static PhoneBookEntry contacts[] = new PhoneBookEntry[100];
int a=0;
int b[] = new int [100];
int count=0;
public void getData()throws IOException
{
FileReader in = new FileReader("phonebookinput.txt");
BufferedReader textreader = new BufferedReader(in);
String sp[];
for(a=0; a<contacts.length; a++)
{
String s = textreader.readLine();
sp = s.split("\t");
contacts[a] = new PhoneBookEntry(sp[0], sp[1], (Integer.parseInt(sp[2])), sp[3], sp[4]);
}
}
public void add(String z, String x, int c, String d, String e)
{
for (int t=0; t<b.length; t++)
{
if (contacts[b[t]].getNumber().equals("XXXX"))
{
contacts[b[t]] = new PhoneBookEntry(z, x, c, d, e);
}
else
{
contacts[a+1] = new PhoneBookEntry(z, x, c, d, e);
a++;
}
}
}
public int searchName(String n)
{
int y=-1;
for (int b=0; b<contacts.length;b++)
{
if (contacts[b].getFirstName().equalsIgnoreCase(n))
{
y=b;
}
else if (contacts[b].getLastName().equalsIgnoreCase(n))
{
y=b;
}
}
return y;
}
public int searchNumber(String m)
{
int x=-1;
for(int d=0; d<contacts.length; d++)
{
if (contacts[d].getNumber().startsWith(m))
{
x=d;
}
else if (contacts[d].getNumber().endsWith(m))
{
x=d;
}
}
return x;
}
public boolean edit(String a, String b, int c, String d, String e, String f)
{
int g=searchName(f);
int h=searchNumber(f);
if (g!=-1)
{
contacts[g].setFirstName(a);
contacts[g].setLastName(b);
contacts[g].setAge(c);
contacts[g].setNumber(d);
contacts[g].setEmail(e);
return true;
}
else if (h!=-1)
{
contacts[h].setFirstName(a);
contacts[h].setLastName(b);
contacts[h].setAge(c);
contacts[h].setNumber(d);
contacts[h].setEmail(e);
return true;
}
else {return false;}
}
public void deleteValue(String u)
{
int g=searchName(u);
int h=searchNumber(u);
if (g!=-1)
{
contacts[g].setFirstName("XXXX");
contacts[g].setLastName("XXXX");
contacts[g].setAge(-1);
contacts[g].setNumber("XXXX");
contacts[g].setEmail("XXXX");
b[count]=g;
}
else if (h!=-1)
{
contacts[h].setFirstName("XXXX");
contacts[h].setLastName("XXXX");
contacts[h].setAge(-1);
contacts[h].setNumber("XXXX");
contacts[h].setEmail("XXXX");
b[count]=h;
}
count = count + 1;
}
public void sortFirstName()
{
for (int r=99; r>=0; r--)
{
for (int h=0; h<=r-1; h++)
{
if (contacts[h].getFirstName().compareTo(contacts[h+1].getFirstName())>0)
{
String temp = contacts[h+1].getFirstName();
contacts[h+1].setFirstName(contacts[h].getFirstName());
contacts[h].setFirstName(temp);
}
}
}
}
public void sortLastName()
{
for (int r=99; r>=0; r--)
{
for (int h=0; h<=r-1; h++)
{
if (contacts[h].getLastName().compareTo(contacts[h+1].getLastName())>0)
{
String temp = contacts[h+1].getLastName();
contacts[h+1].setLastName(contacts[h].getLastName());
contacts[h].setLastName(temp);
}
}
}
}
public void printDetails()
{
String [] columnNames = {"First Name", "Last Name", "Age", "Phone Number", "Email"};
String data [][] = new String [100][5];
for (int u=0; u<data.length; u++)
{
String first = contacts[u].getFirstName();
String last = contacts[u].getLastName();
String age = Integer.toString(contacts[u].getAge());
String number = contacts[u].getNumber();
String email = contacts[u].getEmail();
columnNames[u][0] = first; //Here is where the error comes
columnNames[u][1] = last;
columnNames[u][2] = age;
columnNames[u][3] = number;
columnNames[u][4] = email;
}
JTable table = new JTable (data, columnNames);
table.setEnabled(false);
}
}
columnNames in your code above is a one dimensional String array, but you're attempting to use it as a two dimensional array
columnNames[u][0] = first; //Here is where the error comes
I think you meant to assign values in your loop to the data array instead of the columnNames array, as in
data[u][0] = first;
Related
How can I get the value of int "icon" from the Int values array with an example:
2 = R.drawable.ic_blue?
or: how to get: R.drawable.ic_blue? knowing id: 2?
public class iconsList {
public class IntValues {
public int id;
public int icon;
public IntValues(int id, int icon){
this.id=id;
this.icon=icon;
}
}
IntValues[] icons = new IntValues[] {
new IntValues(0, R.drawable.ic_default),
new IntValues(1, R.drawable.ic_red),
new IntValues(2, R.drawable.ic_blue),
};
}
Add this method to your iconsList class
public IntValues find(int num) {
for (int i = 0; i < icons.length; i++) {
if (num == icons[i].icon) {
return icons[i];
}
}
return null;
}
You can return the index ( i ) or the class IntValues with id..
I've written my first Genetic Algorithm in Java and I'm able to optimize functions with one argument x, but I don't know how to optimize functions with two arguments x and y. Algorithm class and main app works correctly so i send only Individual.java and Population.java. If I think correctly in genes I have only x-coordinate but I'm not sure how to add y-coordinate. Any advise will be helpfull.
Individual.java
public class Individual {
private int[] genes;
private int fitness;
private Random randomGenerator;
public Individual() {
this.genes = new int[Constants.CHROMOSOME_LENGTH];
this.randomGenerator = new Random();
}
public void generateIndividual() {
for(int i = 0; i < Constants.CHROMOSOME_LENGTH; i++) {
int gene = randomGenerator.nextInt(2);
genes[i] = gene;
}
}
public double f(double x) {
// return Math.pow(x,2);
return (Math.pow((1-x),2)) + (100*(Math.pow((1-Math.pow(x,2)),2)));
// return Math.sin(x)*((x-2)*(x-2))+3;
}
public double getFitness() {
double genesToDouble = genesToDouble();
return f(genesToDouble);
}
public double getFitnessResult() {
double genesToDouble = genesToDouble();
return genesToDouble;
}
public double genesToDouble() {
int base = 1;
double geneInDouble = 0;
for( int i =0; i < Constants.GENE_LENGTH; i++) {
if(this.genes[i] == 1)
geneInDouble += base;
base = base*2;
}
geneInDouble = (geneInDouble / 1024) * 10.1;
return geneInDouble;
}
public int getGene(int index) {
return this.genes[index];
}
public void setGene(int index, int value) {
this.genes[index] = value;
this.fitness = 0;
}
}
Population.java
public class Population {
private Individual[] individuals;
public Population(int populationSize) {
individuals = new Individual[populationSize];
}
public void initialize() {
for(int i = 0; i < individuals.length; i++) {
Individual newIndividual = new Individual();
newIndividual.generateIndividual();
saveIndividual(i, newIndividual);
}
}
public Individual getIndividual(int index) {
return this.individuals[index];
}
//maksimum lub minimum
public Individual getFittestIndividual() {
Individual fittest = individuals[0];
for(int i =0; i < individuals.length; i++) {
if(getIndividual(i).getFitness() < fittest.getFitness())
fittest = getIndividual(i);
}
return fittest;
}
public int size() {
return this.individuals.length;
}
public void saveIndividual(int index, Individual individual) {
this.individuals[index] = individual;
}
}
This is what i got
Constructor:
public class Assignment08_ {
String name;
String abrv;
int atomicNumber;
double atomicMass;
int group;
int period;
public Assignment08_(String name, String abrv, int atomicNumber, double
atomicMass, int group, int period) {
this.name = name;
this.abrv = abrv;
this.atomicNumber = atomicNumber;
this.atomicMass = atomicMass;
this.group = group;
this.period = period;
}
}
And the Class:
import java.io.File;
import java.util.Scanner;
public class Assignment08 {
public static void main(String[] args) throws Exception {
Assignment08_[] elementArr = new Assignment08_[119];
reader(elementArr);
for(int i = 0; i < args.length; i++) {
action(elementArr, args[i]);
}
}
public static void reader(Assignment08_[] elements) throws Exception {
Scanner data = new Scanner(new File("/srv/datasets/elements"));
while (data.hasNext()) {
int atomicNumber = data.nextInt();
String abrv = data.next();
String name = data.next();
double atomicMass = data.nextDouble();
int period = data.nextInt();
int group = data.nextInt();
elements[atomicNumber] = new Assignment08_(name, abrv, atomicNumber,
atomicMass, group, period);
}
data.close();
}
public static void action(Assignment08_[] element, String str) {
// for testing
System.out.printf("%s%n", element[4].abrv);
for (int i = 0; i < 119; i++) {
if (str.compareTo(element[i].abrv) == 0)
System.out.println(element[i].name);
}
}
}
i input "java Assignment08_ H" (which is equal to element[0].abrv)
i get the output:
"
Be
Exception in thread "main" java.lang.NullPointerException
at Assignment08.action(Assignment08.java:33)\
at Assignment08.main(Assignment08.java:11)
"
Be = element[4].abrv
and its wierd because if i were to take away that for statement and leave only the nested if statement and change the i to a Number (like 0), it will print the name and run properly( if i input H which equals element[0].abrv), soooo i dont know what going on here, any help would be great, thx
Below is my code and I have notes beside where my errors are showing. Im unsure where I am going wrong when recalling my method or if that is even the issue.
import java.util.Scanner;
public class HurlerUse
{
static Hurler[] hurlerArray;
// find lowest score (static method)
public static int findLow(Hurler[] hurlerArray)
{
for(int i = 0; i < hurlerArray.length; i++)
{
int lowest = 0;
int index = 0;
for(int j=0; j<hurlerArray.length; j++)
{
int current = hurlerArray[i].totalPoints();// issue with my method 'totalPoints'
if(current < lowest)
{
lowest = current;
index = i;
}
}
return index;
}
}
//main code
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
Hurler[] hurlerArray = new Hurler[5];
for (int i = 0; i <4; i++)
{
hurlerArray[i] = new Hurler();
System.out.println ("Enter Hurler Name:");
hurlerArray[i].setName(sc.nextLine());
hurlerArray[i].setGoalsScored(sc.nextInt());
System.out.println("Enter the hurler's goals scored");
hurlerArray[i].setPointsScored(sc.nextInt());
System.out.println("Enter the hurler's points scored");
}
for(int i=0;i< hurlerArray.length; i++)
{
hurlerArray[i] = new Hurler(MyName, MyGoalsScored, MyPointsScored);// issue with all 3 objects in the brackets but im unsure of how to fix them
}
System.out.println("The lowest scoring hurler was " + hurlerArray[findLow(hurlerArray)].getName());// error with my code here I think it is in the method
}
}//end of class
I know the nyName, myGoalsScored, myPointsScored is incorrect but can anyone explain why?
This is the class page that accompanies it
public class Hurler
{
private String name;
private int goalsScored;
private int pointsScored;
public Hurler() //constructor default
{
name ="";
goalsScored = 0;
pointsScored = 0;
}
public Hurler(String myName, int myGoalsScored, int myPointsScored) // specific constructor
{
name = myName;
goalsScored = myGoalsScored;
pointsScored = myPointsScored;
}
//get and set name
public String getMyName()
{
return name;
}
public void setName(String myName)
{
name = myName;
}
//get and set goals scored
public int getGoalsScored()
{
return goalsScored;
}
public void setGoalsScored(int myGoalsScored)
{
goalsScored = myGoalsScored;
}
// get and set points scored
public int getPointsScored()
{
return pointsScored;
}
public void setPointsScored(int myPointsScored)
{
pointsScored = myPointsScored;
}
public int totalPoints(int myGoalsScored, int myPointsScored)
{
int oneGoal = 3;
int onePoint = 1;
int totalPoints = ((goalsScored * oneGoal) + (pointsScored * onePoint));
{
return totalPoints;
}
}
}//end of class
You call totalPoints() without parameters while method totalPoints(int, int) in Hurler class expects two int parameters.
Objects MyName, MyGoalsScored, MyPointsScored are not declared at all.
You call getName() method, while in Hurler class you do not have one. There is method getMyName(), maybe you want to call that one.
I have problem with my code. I wrote program for count words in text, but I have small problem with patterns which must be search in text. Maybe somebody can help me.
import java.util.*;
class KomparatorLicz implements Comparator<Word> {
#Override
public int compare(Word arg0, Word arg1) {
return arg1.amount - arg0.amount;
}
}
class KomparatorString implements Comparator<Word> {
#Override
public int compare(Word obj1, Word obj2) {
if (obj1.content == obj2.content) {
return 0;
}
if (obj1.content == null) {
return -1;
}
if (obj2.content == null) {
return 1;
}
return obj1.content.compareTo(obj2.content);
}
}
class Word
{
public String content;
public int amount;
public Word(String content, int amount) {
this.content = content;
this.amount = amount;
}
#Override
public String toString() {
return "Word [content=" + content + ", amount=" + amount + "]";
}
}
public class Source4 {
public static float procent(int wordCount, int oneWord)
{
return (((float)oneWord*100)/(float)wordCount);
}
public static void main(String[] args) {
String line, wordsLine[];
String klucze = null;
int valTemp;
int wordCount=0;
int keyWords=0;
HashMap<String, Word> slownik = new HashMap<String, Word>();
ArrayList<Word> lista= new ArrayList<Word>();
ArrayList<Object> keyWordsList = new ArrayList<Object>();
Scanner in = new Scanner(System.in);
String alph = in.nextLine();
keyWords = in.nextInt();
for(int i=0; i<keyWords; i++)
{
klucze = in.next();
keyWordsList.add(klucze);
}
while(in.hasNextLine())
{
line = in.nextLine();
if(line.equals("koniec")) break;
wordsLine = line.split("[^" + alph + "]");
for(String s : wordsLine) {
if(s != null && s.length() > 0)
{
wordCount++;
if(slownik.containsKey(s))
{
valTemp = slownik.get(s).amount;
slownik.remove(s);
valTemp++;
slownik.put(s, new Word(s,valTemp));
}
else
{
slownik.put(s, new Word(s,1));
}
}
}
}
for (String key : slownik.keySet())
{
lista.add(slownik.get(key));
}
Collections.sort(lista, new KomparatorString());
StringBuffer result = new StringBuffer();
int keyWordCounter=0;
int amountBuff=0;
float percentBuff=0;
for (int i = 0; i<lista.size();i++)
{
if(keyWordsList.contains(lista.get(i)))
{
result.append(amountBuff+" "+percentBuff+"%");
amountBuff = 0;
percentBuff = 0;
result.append("\n");
result.append(lista.get(i).amount+" "+(procent(wordCount,lista.get(i).amount)+"%"));
result.append(" "+lista.get(i).content);
result.append("\n");
keyWordCounter+=lista.get(i).amount;
}
else
{
amountBuff+=lista.get(i).amount;
percentBuff+=procent(wordCount,lista.get(i).amount);
}
}
result.append(amountBuff+" "+percentBuff+"%");
System.out.println("Wersja AK");
System.out.println(keyWords+" różnych słów kluczowych");
System.out.println(wordCount+" wystąpień wszystkich słów");
System.out.println(keyWordCounter+" "+procent(wordCount,keyWordCounter)+"% "+" wystąpień słów kluczowych");
System.out.println((wordCount-keyWordCounter)+" "+procent(wordCount,(wordCount-keyWordCounter))+"% wystąpień innych słów");
System.out.println(result);
}
}
It's wrong code if(keyWordsList.contains(lista.get(i))).
You need if(keyWordsList.contains(lista.get(i).content)).