I was hoping if you can help me with this coding. I'm attempting to create a bar chart but it doesn't seem to be going my. I m trying to make the output below but when I run it I get [Red, Yellow, Blue](0) repeating. I feel like I'm close to solving this. If someone can push me in the right direction in what I can do it would be appreciated greatly.
import java.util.HashSet;
import java.util.Arrays;
import java.util.Set;
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//These arrays are not to be modified and should only use these 2 arrays.
short[] points ={1,2,1,1,1,1,1,1,3,4,1,5};
String[] teams ={"Red","Yellow","Blue","Blue","Blue","Red","Yellow","Red","Yellow","Red","Blue","Blue"};
Set<String> uniqueTeams = new HashSet<String>(Arrays.asList(teams));
Barchart(points, teams, uniqueTeams);
}
public static void Barchart(short[] points, String[] teams, Set<String> uniqueTeams){
byte count=0;
for(int index=0; index < points.length; index++){
if(teams.equals(uniqueTeams)){
count++;
}
}
for(int index=0; index < points.length; index++){
System.out.println(uniqueTeams + "("+ count + ")");
}
}
}
//Output should look like this:
//
//Red(7): *******
//
//Yellow(6): ******
//
//Blue(9): *********
I have a idea of how to do it another way but I don't know how. If someone can answer this question below.
How would I be able to get or create a new array without having doubles of what I do in the teams array? So the array would look like String[] uniqueTeams = {"Red, "Yellow", "Blue"}; but not initialize or declare it but create a way to make the program create itself if that makes sense.
You're printing out uniqueTeams directly. uniqueTeams is of type Set. What you should be doing is cycling through each of the items inside the set, and printing out the stars next to them.
The OOP Approach
If it were me, I would not have everything in separate data structures, it makes for very messy code. Why not create a Bar object, that will contain the value and the name. Then you simply need to cycle through a collection of type Bar and call the toString() method`, which you will override.
While I'm here
I figure I might as well give you a step by step with the OOP approach. With Object Oriented Programming, we want to contain similar data in objects. For example, the name and value of a bar is a great object to make; all the data relates to the class.
class Bar
{
private int count;
private String name;
// Some values here to store the count and the name of the bar.
public Bar(String name, int count)
{
// Assign those values in the constructor.
this.name = name;
this.count = count;
}
// Override the Object toString() method, and replace it with our code:
public String toString()
{
String stars = "";
for(int x = 0; x < count; x++)
{
stars += "*";
}
// Create the stars string, and append it to the name and count.
return name + ":" + count + " | " + stars;
}
}
Now to access this code is much, much simpler than your solution. First, we create an ArrayList, something like barChart to store all the values, and we parameterize it to type Bar:
ArrayList<Bar> barChart = new ArrayList<Bar>();
Then we can add some test cases in:
barChart.add(new Bar("Red", 10));
barChart.add(new Bar("Blue", 20));
barChart.add(new Bar("Green", 12));
Now, because you have overridden the toString method, you can now simply pass the objects to a System.out.println() function. Something like:
for(Bar b : barChart) {
System.out.println(b);
}
Output
Red:10 | *********
Blue:20 | ********************
Green:12 | ************
Related
I am new to Java programming and I had a task in class.
So the main thing was I had to make a public class named BankAccount with these 3: int number, String owner, int amount.
Then I had to make an array of 10 with this class and fill it up (the owner names were Name1, Name2, etc.).
Then I had to make a String array of 5 with 5 names in it (for example: "James", "Jack", etc.)
and then I had to kind of "modify" the owner names so that my program will attach one of the 5 names randomly to the end of the current owner names.
So it will be like this for example: Name2Jack, Name3James, etc.
I successfully did all of this.
But then.
My teacher told me to make another method which will decide, how many names do I have out of the 10 ownernames in which name X is present.
So I did this:
public static int Count(BankAccount[] accounts, String name){
int number=0;
for (i=0; i<accounts.length, i++){
if(accounts[i].owner.contains(name)==true)
number++;
}
return number;
}
At least if I remember correctly, it was this. Or something similar like that.
And this worked as well.
But then, my teacher said, how would I do it with not .contains but with .equals ?
And if I would do it with that, would I need 1 or 2 "=" marks?
I had no idea what she means, like I dont know how to do it with .equals... because the owner names are like Name1Jack for example..
She told me I would need 1 "=" mark instead of 2, and that I should look after this for the next class.
Can you guys actually tell me what she meant with this ".equals" method instead of the .contains one?
How could I do this with .equals , and I dont get it why would I need 1 "=" mark instead of 2 whatsoever.
Any help would be really appreciated!
It appears that you need to just change this one line:
From:
if (accounts[i].owner.contains(name) == true)
To:
if (accounts[i].owner.equals(name))
Here is a sample code with both variations:
public class BankAccountDemo {
public static void main(String[] args) {
BankAccount[] bankAccounts = new BankAccount[5];
bankAccounts[0] = (new BankAccount(1, "Name1James", 1000));
bankAccounts[1] = (new BankAccount(2, "Name2Jack", 2000));
bankAccounts[2] = (new BankAccount(3, "Name3Henry", 3000));
bankAccounts[3] = (new BankAccount(4, "Name4Jack", 4000));
bankAccounts[4] = (new BankAccount(5, "Name5James", 5000));
System.out.println("Check A:");
System.out.println(BankAccountDemo.Count(bankAccounts, "James"));
System.out.println(BankAccountDemo.Count2(bankAccounts, "James"));
System.out.println("Check B:");
System.out.println(BankAccountDemo.Count(bankAccounts, "Name5James"));
System.out.println(BankAccountDemo.Count2(bankAccounts, "Name5James"));
}
public static int Count(BankAccount[] accounts, String name) {
int number = 0;
for (int i = 0; i < accounts.length; i++) {
if (accounts[i].owner.contains(name) == true) {
number++;
}
}
return number;
}
public static int Count2(BankAccount[] accounts, String name) {
int number = 0;
for (int i = 0; i < accounts.length; i++) {
if (accounts[i].owner.equals(name)) {
number++;
}
}
return number;
}
}
Run output is:
Check A:
2
0
Check B:
1
1
The code is :
package classes;
public class Test {
private static double mutationRate = 0.5;
public static void main(String[] args) {
Population pop = new Population();
pop.initialise();
Population po = new Population();
po.getIndividusList().add(pop.getFittest());
po.getIndividusList().add(mutate(pop.getIndividusList().get(1)));
}
private static Chromosom mutate(Chromosom l) { // changer les couples d'interventions des parcs)
// loop through genes
Chromosom ch = new Chromosom();
for (int i = 0; i < l.size(); i++)
ch.put(i, l.get(i));
for (int i = 0; i < ch.size(); i++) {
double alea = Math.random() * 13;
int moisIntervention1 = (int) alea;
Intervention interv1 = new Intervention(1, moisIntervention1);
ch.get(i).modInterventions(ch.get(i).intervention2(interv1));
}
return ch;
}
}
The problem is that I did not change the instance pop but when I change the other instance po, pop changes too.
java pass by value.
when you call this mutate(pop.getIndividusList().get(1))
you are sending pop's instance, so it will get change.
Supose pop.getIndividusList().get(1) return String varibale do this way
String var=pop.getIndividusList().get(1);
then call mutate(var)
I'm unsure about whether I understood the problem, but I think that you mean that when you alter the items in Population po, the items in Population pop mirror those changes.
That is, indeed, the expected behavior of your code: to populate po, you are adding items from pop - (pop.getFittest, pop.getList.get(1) ).
But the individuals are, I believe, instances of objects, so add/remove and similar operations work with references to the objects, and not with copies of them. Therefore, as you have 2 references to the same obj, any change is mirrored.
IF you want to create a copy, you should add to po a new object with the same state, either by creating a constructor that takes another instance as parameter, implementing a copy method, or something similar.
It should be something like this:
Population po = new Population();
Individual fittest = pop.getFittest();
Individual poCopy = new Individual();
//ADD CODE HERE TO COPY ALL THE FIELDS FROM fittest TO poCopy
//....
po.getIndividusList().add(poCopy);
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!
I'm having a difficult time figuring how to display the shared personArray with the appropriate course object. For example, I need to display a list of a course and the people that are in that course, and again for the next course. I feel that there's something wrong with my nested for loop or the personCount variable because not every course has the same amount of people so how do I deal with this?
Hopefully you all can get a clear picture of the stripped down code below.
Note* I must use aggregation and toStrings, and not allowed to use lists, arraylists, or scanner.
Thanks!
public class School {
private static Course[] courseArray = new Course[5];
public static void printList(){
String print = "";
for (int x = 0; x < courseCount; x++) {
print += courseArray[x].getCourseName() + "\n";
for (int y = 0; y < personCount; y++){
print += courseArray[y].personArray[y].getPersonName()+ "\n";
//^ I thought I could use the 1st forloop index to stay in the 1 course and print out all the people for that course(like the hardcode example below) but I get a nullpointer
}
}
JOptionPane.showMessageDialog(null,print);
/*
If I hardcode the print String like below I get the correct output.
So I know my objects are being stored properly, but I can't figure out how to get the correct display with a loop
print += courseArray[0].personArray[0].getPersonName(); //tim (bio)
print += courseArray[0].peopleArray[1].getPersonName(); //bob (bio)
print += courseArray[1].peopleArray[2].getPersonName(); //john (art)
*/
}
}
------------------------
public class Course {
private Person[] personArray = new Person[50];
//constructor for course
// get/set courseName methods
public String toString(){
// not sure how to use this the right way
}
}
-----------------------------------
public class Person extends Course {
//constructor for person
// get/set personName methods
public String toString(){
return getPersonName();
}
}
Make sure that all 50 of the people in your personArray are initialized first; check to see if they are by printing out the entire array like so (you will need to import java.util.Arrays):
System.out.println(Arrays.toString(course[x].personArray));
If that gives back any "null" values then you know that not every single Person in the PersonArray was initialized first.
You should change courseCount to courseArray.length and personCount to courseArray.getPersonArraySize() and implement getPersonArraySize() in Course class to return length of personArray.
replace your loops with these below..
for (Course c : courseArray) {
print += c.getCourseName() + "\n";
for (Person p : c.personArray){
print += p.getPersonName()+ "\n";
}
}
I want to create a 2D Array that creates a mini seating chart of an airplane. So far, I've gotten it to successfully print out something that looks like this:
1A(0) || 1B(0) || 1C(0)
2A(0) || 2B(0) || 2C(0)
3A(0) || 3B(0) || 3C(0)
4A(0) || 4B(0) || 4C(0)
The zeroes represent an empty seat, and the number one is used to represent an occupied seat.
I first created the program with arrays that were class variables for a First Class, but I wanted to make this program usable for an Economy Class section. The only difference between the two sections is the size of the array so I edited my code to look like this:
public class Seating
{
private int FIRSTCLASS= 12;
private int ECONOMYCLASS= 240;
private int occupied, column;
private String[][] seatchart;
private int[][] seatlist;
private String[][] namelist;
private String name;
public String customer;
public Seating(String seatclass)
{
seatclass.toUpperCase();
if (seatclass.equals("FIRSTCLASS"))
{
seatchart= new String[FIRSTCLASS/3][3];
seatlist= new int[FIRSTCLASS/3][3];
namelist= new String[FIRSTCLASS/3][3];
}
else
if (seatclass.equals("ECONOMY"))
{
seatchart= new String[ECONOMYCLASS/3][3];
seatlist= new int[ECONOMYCLASS/3][3];
namelist= new String[ECONOMYCLASS/3][3];
}
}
public void Creation()
{
for (int i=0; i< seatlist.length; i++)
{
for (int j=0; j<seatlist[i].length; j++)
{
seatlist[i][j]= 0 ;
}
}
I get an null pointer exception error around for (int i=0; i< seatlist.length; i++)
How can I fix this error?
Thanks in advance!
The problem is with this line:
seatclass.toUpperCase();
Replace it with:
seatclass = seatclass.toUpperCase();
I think you are creating the class with a string like "firstclass" rather than "FIRSTCLASS" right? Those aren't the same strings and just invoking the toUpperCase method on the string without assigning the result to a variable to then be tested means nothing happens.
Then since none of your if conditions are met, the arrays are not initialized and a null pointer exception is thrown when Completion() is called.
I'm not sure if you are new to java programming, but I wanted to add a few recommendations to your class:
public class Seating {
private static int FIRSTCLASS= 12; // Make these constants static since they pertain to all
private static int ECONOMYCLASS= 240; // instances of your class. That way there is exactly on
// copy of the variables, which is more memory efficient.
private int occupied;
private column; // Okay but Java convention is to declare each member variable on its own line
// increases code readability.
private String[][] seatchart;
private int[][] seatlist;
private String[][] namelist;
private String locSeatClass;
private String name;
public String customer; // Okay but better to leave this private and then provide getter and
// setter methods to provide access to this string. Much easier to track
// down who is changing its value in your code.
public Seating(String seatclass) { // Java convention is to place the opening bracket here not
// on the next line.
// Make sure that seatClass is not null or empty. NOTE: This is a neat trick for
// simultaneously checking for both null and empty strings in one shot. Otherwise, you have
// you have to check for null and then examine the string's length which is more code.
if ("".equalsIgnoreCase(seatClass) {
throw new IllegalArgumentException("Seat class undefined.");
}
// Store the seat class in a member variable for use. Could also be a local variable.
// My original solution is problematic because it changes the original value of the seat
// class that was passed into the constructor (you might want that information).
locSeatClass = seatclass.toUpperCase();
if (locSeatClass.equals("FIRSTCLASS"))
{
seatchart= new String[FIRSTCLASS/3][3];
seatlist= new int[FIRSTCLASS/3][3];
namelist= new String[FIRSTCLASS/3][3];
}
else if (locSeatclass.equals("ECONOMY")) {
seatchart= new String[ECONOMYCLASS/3][3];
seatlist= new int[ECONOMYCLASS/3][3];
namelist= new String[ECONOMYCLASS/3][3];
}
else {
// Throw an exception if someone passes in an unknown seat class string.
throw new IllegalArgumentException("Unknown seat class detected.")
}
}
public void creation() { // NOTE: Java convention is to begin method names with a lower
// case letter.
// This method is unnecessary. Arrays of integers are initialized with an initial value
// of zero by default. However, if you want to make your class reusable, you could change
// change the name of the this method to clear, which would allow you to clear the arrays of
// an existing object.
for (int i=0; i< seatlist.length; i++)
{
for (int j=0; j<seatlist[i].length; j++)
{
seatlist[i][j]= 0 ;
}
}
}
The only way that line of code can generate a NPE is if seatlist is null. Unless you assign null to seatlist somewhere else in your class, the only way it can be null is if the argument that you pass to the Seating constructor does not match either "FIRSTCLASS" or "ECONOMY". Check your call to the constructor. Also, you might want to just use seatclass.equalsIgnoreCase().
You should modify your constructor to at least warn about that eventuality, since it is vital to the proper operation of the class that any instances of Seating have valid seatlist and namelist arrays.