This question already has answers here:
Best way to convert an ArrayList to a string
(27 answers)
Closed 3 years ago.
So I am having trouble trying to loop through an array list but i dont want to use a println statement to print the elements from the array list. Is it possible if i could store all the elements into a local variable through each loop and then return the local variable when i call the method later on?e
Here is my code:
public String displayProperties() {
String property = null;
for (int i = 0; i < properties.size(); i++) {
property = properties.get(i);
}
return property;
}
You would have to introduce an instance variable in order to cache the result of your method (your local variable doesn't live past the current execution of the method).
And you'd also need to change the logic of that method, to append all the elements into a single String.
I also suggest adding some separator between the elements.
private String cachedProperties = null;
public String displayProperties() {
if (cachedProperties == null) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < properties.size(); i++) {
if (i > 0) {
sb.append(',');
}
sb.append(properties.get(i));
}
cachedProperties = sb.toString();
}
return cachedProperties;
}
Note that if the properties List may change, you have to reset your cache instance variable each time that happens.
May be modify the code to get the final string as below
property += properties.get(i);
property += " "
This question already has answers here:
Default or initial value for a java enum array
(5 answers)
Can we assume default array values in Java? for example, assume that an int array is set to all zeros?
(4 answers)
Closed 4 years ago.
I created an enum array like this:
enum MyEnums {
FIRST, SECOND, THIRD, FOURTH;
}
public class MyEnumsTest {
public static void main(String[] args) throws Exception {
MyEnums[] myEnums = new MyEnums[4];
for(int i = 0; i< myEnums.length; i++) {
System.out.println(myEnums[i]);
}
}
}
But why is the output null, null, null and null? And how can I get the element by myEnums[i].FIRST?
What you're doing here is creating an array of MyEnums, and the default value is null (you haven't set the values in the array).
If you wanted to print out the enum values you can use the values() method:
for(MyEnums en : MyEnums.values()) {
System.out.println(en);
}
or (more like your original code)
for(int i = 0; i < MyEnums.values().length; i++) {
System.out.println(MyEnums.values()[i]);
}
This prints:
FIRST
SECOND
THIRD
FOURTH
This question already has answers here:
Why am I not getting a java.util.ConcurrentModificationException in this example?
(10 answers)
Closed 7 years ago.
I am trying to add "Luis" 3 times to array list and then remove "Luis" so there is only one "Luis". Seems to be a problem with the if.
import java.util.ArrayList;
public class Menu {
private ArrayList<String> meals;
public Menu() {
this.meals = new ArrayList<String>();
}
// Implement the methods here
public void addMeals() {
this.meals.add("Luis");
this.meals.add("Luis");
this.meals.add("Luis");
for (String container : this.meals) {
for (int counter = 0; counter < this.meals.size(); counter++) {
***if (counter > 1 && this.meals.contains(container)) {
this.meals.remove(this.meals.indexOf(container));
}***
}
}
System.out.println(this.meals);
}
}
An ArrayList can contain duplicates. There are other Java collection classes which can only contain unique elements, such as Set.
I'd suggest you look at the documentation for Set and its implementations, this would likely solve your issue.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I am new to Java and have just beginning doing some exercises a friend sent me. The exercise in question asks us to create a class Term for the terms of a polynomial, and another the class Polynomial itself, where the polynomial is represented as a fixed size array and the values of its fields are provided. I have written the following code:
class Term
{
int coeff;
int exponent;
}
public class Polynomial {
static int size=5;
Term[] poly;
public Polynomial()
{
poly = new Term[size];
for(int i=0;i<size;i++)
{
poly[i].coeff=0;
poly[i].exponent=0;
}
}
public static void main(String args[]) throws Exception
{
Polynomial p = new Polynomial();
}
}
And I keep getting the following exception:
Exception in thread "main" java.lang.NullPointerException
at prac.polynomial.<init>(polynomial.java:25)
at prac.polynomial.main(polynomial.java:34)
Please help me with what I am doing wrong here.
Array elements for an Object array are nullby default. Make sure they are initialized before attempting to access their fields
for (int i = 0; i < size; i++) {
poly[i] = new Term();
...
}
You created the array of Terms, but it's initialized to all nulls. You need to create your Terms.
for(int i=0;i<size;i++)
{
poly[i] = new Term();
poly[i].coeff=0;
poly[i].exponent=0;
}
I'm quite new to arrays and methods, and I've been seeing this error recurring through several programs: error '[' expected.
In each occasion, it seems to correct itself as I adjust something else, but in this particular case, I am completely stumped.
By the way, I am using several methods and arrays to create a quiz (before you ask, yes, this is an assignment and I agree, a list is a better way to handle this data - but that is not an option).
It is possible that I am not passing the arrays correctly between methods, as I'm a little muddy on that process. From my understanding, in order to send/receive (i.e. import/export) an array or other variable between methods, I must declare that variable/array in the method header parameters.
import java.util.Scanner;
public class H7pseudo
{
public static void main(String[] args)
{
//call getAnswerkey method
getAnswerkey(answerkey[i]);
//call getAnswers method
getAnswers(answers[i]);
//call passed method? necessary or no?
boolean passed = passed(answerkey[i], answers[i], qMissed[i], points);
//Print results of grading
if (passed)
{
System.out.println("Congratulations! You passed.");
}
else
{
System.out.println("Try again, sucka. You FAILED.");
}
//call totalPoints
totalIncorrect(points);
//call questionsMissed
questionsMissed(qMissed[i]);
}
//get answer key (create answerkey array & export)
public static void getAnswerkey(answerkey[i])
{
//create answerkey array here
char[] answerkey;
//determine number of questions (indices)
answerkey = new char[20];
//input values (correct answers) for each index
//for our purposes today, the answer is always 'c'.
for (int i = 0; i <=20; i++)
{
answerkey[i] = 'c';
}
}
//get student answers (create answers array & export)
public static void getAnswers(answers[i])
{
//initialize scanner for user input
Scanner scan = new Scanner(System.in);
//create answer array here
char[] answers;
//determine number of questions (indices)
answers = new char[20];
//prompt for user input as values of each index
for (int i = 0; i <= 20; i++) {
answers[i] = scan.nextChar();
}
}
//grade student answers (import & compare index values of arrays:answers&answerkey
//create & export qMissed array
public static boolean passed(answerkey[i], answers[i], qMissed[i], points)
{
int points = 0;
//create new array: qMissed
boolean[] qMissed;
//determine number of questions to be graded
qMissed = new boolean[20];
//initialize values for array
for (int i = 0; i <= 20; i++) {
qMissed[i] = false;
}
//cycle through indices of answerkey[i] & answers[i];
for (int i = 0; i =< 20; i++)
{
if (answers[i] == answerkey[i])
{
correct = true;
points = points+1;
qMissed[i] = true;
}
else {
qMissed[i] = false;
}
}
//evaluate whether or not the student passed (15+ correct answers)
if (points >= 15)
{
passed = true;
}
else
{
passed = false;
}
return passed;
}
public static void totalIncorrect(points)
{
int missed = 20 - points;
System.out.println("You missed " + missed + " questions.");
}
public static void questionsMissed(qMissed[i])
{
// for each index of the array qMissed...
for (int i = 0; i < qMissed.length; i++)
{
//...print correct and false answers.
system.out.println(i + ": " + qMissed[i] + "\n");
}
}
}
You can't define array size in the method signature, in Java.
public static void getAnswerkey(answerkey[i])
You can't put anything inside the [] in a method declaration. Also, you have to mention the type:
public static void getAnswerKey(char[] answerkey)
This is not the only reason your code won't work as intended, but I'll leave the rest as part of the exercise.
Look at your method definitions:
public static void questionsMissed(qMissed[i])
This is wrong. You should define the type of the variable and it should not contain [i] like an element of an array. It should be something like this:
public static void questionsMissed(int qMissed)
Or if you want to pass the array, write it like this:
public static void questionsMissed(int[] qMissed)
Apart of this, there are other several errors in your code:
getAnswerkey(answerkey[i]); //answerkey is not defined
getAnswers(answers[i]); //answers is not defined
It would be better if you start reading a Java tutorial first.
I want to vote up Luiggi's answer, but I don't have enough reputation to do that :)
Congrats, cordivia, on getting started with Java!
Here is how an array is declared:
type[] arrayName = new type[numberOfElements]
For example, you did this right in your method definition for getAnswerkey():
char[] answerkey;
answerkey = new char[20];
The part in the method definition inside the parentheses defines the kind of data the method is willing to accept from the outside. So if you don't need to put something into the method to get something out of it, you don't need to put anything in the parentheses. Define the method like this:
getAnswerkey() {
...But that's not the whole story. If you want to get something out of the method, it needs to have a return type as well. A return type is what you're gonna get out of the method when the method's done doing it's magic. For example, if you want to get an int array out of a method you would do something like this:
public static int getTheInteger() {
Since you want an array of chars from the method, you'll want to do something like this:
public static char[] getAnswerkey() {
So that's how you get a method to give you something back. If don't want anything back, you put void:
public static void noMarshmallows() {
Now, when you use the method, you're gonna need to do something with what it gives you, or it did all that work for nothing. So you need to store the return value in a variable when you call the array (calling methods is what you've been doing in main). You know how to store something in a variable. You use the '=' operator:
int myVeryFavoriteNumber;
myVeryFavoriteNumber = 5;
So, you do the same thing when you're getting something out of an array. You assign the return value to a variable. If you want to do this with an array, do this:
int[] myFavs;
myFavs = getMyFavoriteNumbers();
Same with chars:
char[] answerKey;
answerKey = getAnswerKey();
Voila! Your answer key is now right out in the open for the rest of main to see :)
Now, if you want to put something into a method and have it do something with what you put in, you define a parameter. You know how this works. It's just like declaring a variable, and that's exactly what it is. Parameters go in the parentheses and only the method using the parameter sees that variable name (it's local). Something like this:
public static void plusOneToAll (int[] numbers) {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = numbers[i] + 1;
}
}
Notice int[] numbers in the parentheses. The type being passed in is int[] or integer array. numbers is just the parameter name. It functions just like a variable, but it is declared locally (inside the parentheses) and use locally (inside the method). So, if you wanted to compare the answers from two arrays and return the number of matches (like a total score for instance), you would do something like this:
public static int getTotalScore (char[] correctAnswers, char[] userAnswers) {
int totalScore = 0;
for (int i = 0; i < correctAnswers.length; i++) {
if (userAnswers[i] == correctAnswers[i]) {
totalScore = totalScore + 1;
}
}
return totalScore;
}
Notice the return type: int (written before the method name). Inside the array I'm using the variable totalScore to keep track of the number of times the answers match. The method takes two char arrays from the outside and uses them on the inside. Finally, I return an int: totalScore. That kicks the value of totalScore back out to whatever called it (main).
If I might add one last thing: Do yourself a favor and go pick up a copy of Head First Java. It's hard to find a good tutorial online and Java textbooks are just plain boring. The Head First series are kind of like coloring books for adults.
Best of luck!