Getting a Java Array <init> - java

I have a class that has a constructor of the same name, and I'm trying to set all Index Array to "Open" first.
public static void main(String[] args) {
Calendar info = new Calendar();
}
class Calendar{
private String name;
Calendar[] test= new Calendar[24];
Calendar(){
for(int i = 0; i < test.length; i++){
test[i] = new Calendar();
test[i].name = "Open";
}
}
}

The problem is with the recursive calls of Calendar() constructor. Try the below code which uses another constructor for initialising test[] array:
public static void main(String[] args) {
Calendar info = new Calendar();
}
class Calendar {
private String name;
Calendar[] test= new Calendar[24];
Calendar() {
for(int i = 0; i < this.test.length; i++){
this.test[i] = new Calendar("Open");
}
}
Calendar(String name) {
this.name = name;
}
}

Related

I'm trying to send arrays between 2 sheets in Java and toString

Cannot make a reference to the nonstatic method toString() other is saying that I can't have a static toString but when I change it and go to the main it says I need a static toString. I was wondering if anyone could make sense of it because I referenced multiple codes and notes from classes but could not understand.
import java.util.Scanner;
import java.util.Arrays;
class Main
{
public static void main(String[] args)
{
String[] answer = new String();
answerArray();
Quiz Quiz1 = new Quiz();
Quiz.toString();
System.out.print("Number of Correct Answers: ");
System.out.println(Quiz.totalCorrect(answerArray[]));
System.out.print("Number of Mistakes: ");
System.out.println(Quiz.totalMistakes(answerArray[]));
System.out.println("The Student is"+Quiz.isPassing());
}
public static String answerArray()
{
Scanner scan = new Scanner(System.in);
String[] answerArray = new String[10];
for (int i = 0; i < answerArray.length; i++)
{
System.out.println("Enter Grade "+i+1);
answerArray[i]=scan.next;
answerArray[i]=answerArray[i].toLowerCase();
}
return answerArray;
}
}
Quiz Class:
import java.util.Arrays;
class Quiz
{
public static void main(String[] args) {
String[] answerKey = new String[10];
String[] studentAns = new String[answerKey.length];
answerKey[0] = B;
answerKey[1] = D;
answerKey[2] = C;
answerKey[3] = A;
answerKey[4] = E;
answerKey[5] = A;
answerKey[6] = B;
answerKey[7] = A;
answerKey[8] = E;
answerKey[9] = B;
}
public static void studentAns(String answerKey[])
{
for (int i = 0; i < answerArray.length; i++)
studentAns[i]=answerKey[i];
for (int i=0; i<answerKey.length;i++)
studentAns[i]=studentAns[i].toUpperCase();
}
public static String getstudentAns()
{
return studentAns;
}
public static int totalCorrect(String answerArray[])
{
int numCorrect=0;
for (int i = 0; i < answerArray.length; i++)
{
if (answerArray[i].equals(studentAns[i]))
numCorrect=numCorrect+1;
}
return numCorrect;
}
public static int totalMistakes(String answerArray[])
{
int numMistakes=0;
for (int i = 0; i < answerKey.length; i++)
{
if (answerArray[i]!=studentAns[i])
numMistakes=numMistakes+1;
}
return numMistakes;
}
public static boolean isPassing()
{
if (totalCorrect-numMistakes>=7)
return PASSED;
else
return FAILED;
}
public static String toString(String answerArray[])
{
String firstLine = "ANSWER KEY \t Student's Answers";
for (int i = 0; i < answerKey.length; i++)
{
String full=(i+1)+") "+answerArray[i]+"\t\t"+(i+1)+studentAns[i]+"\n";
return full;
}
}
}
Here you are trying to use a static method toString() but that does not exist because classes only have the nonstatic method toString().
Quiz.toString();
To use your static method you should write this instead:
Quiz.toString(answerArray());

Java Objects in Array List

i would like to run the update function automatically for every object i create. What do I have to change in my code, unfortunately it doesn't work
How can I initialize an object in my ArrayList?
:(
Creating an Arraylist and initialize with name
public class Main {
public static void main(String... args) {
Zuhoerer Maria = new Zuhoerer("Maria");
Zuhoerer Sepp = new Zuhoerer("Sepp");
Zeitansager.sagAn();
}
}
class Zuhoerer {
private String name;
private String Ansager;
Zuhoerer(String name) {
this.name = name;
}
private void setAnsager(String datumstring) {
Ansager = datumstring;
}
void update() {
setAnsager(Zeitansager.getZeit());
Zeitansager.schreibeEin(name);
System.out.println(name + " hat gerade die die Zeitansage gehört:
[Datum/Uhrzeit]: " + Ansager);
Zeitansager.trageAus(name);
}
}
class Zeitansager {
private static String datumString;
private static ArrayList<String> abonnenten;
Zeitansager(String datumString) {
Zeitansager.datumString = datumString;
abonnenten = new ArrayList<>();
}
static void schreibeEin(String name) {
abonnenten.add(name);
}
static void trageAus(String name) {
abonnenten.remove(name);
}
static void sagAn() {
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.YYYY' 'HH:mm:ss");
String datum = sdf.format(new Date());
datumString = datum;
for (int i=1; i <= abonnenten.size(); i++) {
abonnenten.update();
}
}
static String getZeit() {
return datumString;
}
}
update function is not called
Your ArrayList in Zeitansager have to be of type Zuhoerer rather than String.
Then in your loop in sagAn() you need to invoke:
abonnenten.get(i).update();
instead of:
abonnenten.update();
Finally your method static void schreibeEin(String name), should actually take a Zuhoerer as an argument.
To run "update" function every time you create an object you must put a call to this function inside your constructor. Like this:
Zuhoerer(String name) {
this.name = name;
update();
}
What are you trying to do with your arraylist? Give me more details so I can try to help you.

using loop variables with object variables

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

How to return an array in .toString method

How can I return an array in this .toString method of my Shelf class?
public class Book
{
int wys, szer;
String imie, tytul;
public Book(int wys, int szer, String imie, String tytul)
{
this.wys = wys;
this.szer = szer;
this.imie = imie;
this.tytul = tytul;
}
#Override
public String toString()
{
return imie;
}
}
public class Shelf
{
int wys;
private Book book[] = new Book[20];
public Shelf(Book[] ks, int j)
{
for (int i = 0; i < ks.length - 1; i++)
{
this.book[i] = ks[i];
}
}
#Override
public String toString()
{
for (int i=0;i<book.length;i++)
{
return book[i].toString();
}
}
}
Main class
public class Test
{
public static void main(String[] args)
{
Book ks[]={
new Book (13,2, "Rhonda Byrne", "Sekret"),
new Book(12, 1, "Graham Greene", "Monsignore Kichote"),
new Book(19, 3, "Hugo Steinhaus", "Slownik racjonalny"),
new Book(10, 4, "RE.M. Remarque", "Trzej towarzysze"),
new Book(13, 3, "A.A. Milne", "Kubus Puchatek"),
new Book(11, 4, "Paulo Coelho", "El Aquimista"),
new Book(13, 5, "Mitch Albom", "Tuesday with Morrie"),
new Book(11, 2, "John Fowles", "Mag"),
};
Shelf s = new Shelf(ks, 15);
System.out.println(s);
}
}
It is doesn't want to compile if the return statement is in the loop.
It will compile if I return in that way:
return book[0].toString+book[1].toString... etc....
But how to do it automatically?
--->I Updated all of the code of a class.
The Arrays utility class has a method to create a string from an array.
return Arrays.toString(book);
public String toString()
So you must return a String.
I suggest using A StringBuilder and Appending to it in your loop.
public String toString()
{
StringBuilder sb =new StringBuilder();
for (int i=0;i<book.length;i++)
{
sb.append(book[i].toString());
}
return sb.toString();
}
You are getting A NullPointerException Because of the way you initialize your Array
private Book book[] = new Book[20];
Change That to something like this:
private Book book[] ;
public Shelf(Book[] ks, int j)
{
book=new Book[ks.length];
for (int i = 0; i < ks.length ; i++)
{
this.book[i] = ks[i];
}
}
Maybe calling the method in a loop?
Then you need a parameter and you can use the method on every element of the array.
for (int i=0; i<book.length; i++) {
toString(int i);
}
And the method:
public String toString(int i) {
return book[i].toString();
}
Not nice, but maybe it helps.
This day and age, I would suggest something along these lines:
#Override
public String toString() {
return Arrays.stream(book).map(Book::toString)
.collect(Collectors.joining(", "));
}

How can I add info to a object class?

class Client{
String name;
Client(String name){
this.name=name;
}
Client (){
name=null;
}
}
class Cashier{
LinkedList <Client> cashierclients;
Cashier(LinkedList<Client> cashierclients){
this.cashierclients=cashierclients;
}
Cashier(){
//this.cashierclients=null;
}
}
class test{
public static void main(String args []){
LinkedList<Client> l=new LinkedList<Client>();
//i do some scans here to add the names of persons to the LinkedList l
Cashier [] cashier=new Cashier[numberofcashiers];
for(int i=0;i<numberofcashiers; i++){
cashier[i]=new Cashier();
}
Now I want to add a client to cashier[0] i do this:
cashier[0].cashierclients.addLast(l.get(0));
everything works fine but when I want to print the size of cashier[1] it returns 1 but it should return 0 because I did not add any person to cashier[1]. Any ideas as to what is wrong?
// the error happens here
cashier[1].cashierclients.size();
the program is working now and it shows the error in cashier[1] size that should return 0 instead of 1
import java.util.*;
class Client {
String name;
Client(String name) {
this.name = name;
}
Client() {
name = null;
}
}
class Cashier {
LinkedList<Client> cashierclients;
Cashier(LinkedList<Client> cashierclients) {
this.cashierclients = cashierclients;
}
Cashier() {
//this.cashierclients=null;
}
}
public class test {
public static void main(String args[]) {
LinkedList<Client> l = new LinkedList<Client>();
// i created this LinkedList to solve the nullpointerexception error
LinkedList<Client> empty =new LinkedList<Client>();
Client client1=new Client("Person1");
l.addLast(client1);
Cashier[] cashier = new Cashier[10];
for (int i = 0; i < 10; i++) {
cashier[i] = new Cashier();
}
// i did this to solve the nullpointerexception error
for(int i=0; i<10; i++){
cashier[i].cashierclients=empty;
}
cashier[0].cashierclients.addLast(l.get(0));
System.out.println(cashier[1].cashierclients.size());
//this should return zero
System.out.println(cashier[1].cashierclients.size());
}
}
The following code
for(int i=0; i<10; i++){
cashier[i].cashierclients=empty;
}
makes cashier[i].cashierclients point to the same object
so you can find
System.out.println(cashier[0].cashierclients == cashier[1].cashierclients);
equals to true
i think you shall change empty to new LinkedList()
that will fix the probelm

Categories

Resources