I have a working code but my output doesn't count up.
Here is the code I am working with:
for(Course course : courses) {
for(int i=0;i<1;i++) {
System.out.println("[" + (i+1) + "]" + course.getCode() + "(" + course.getCreditHour() + ")");
}
}
System.out.print("Enter your choice : ");
I need the (i+1) to count from one to 7.
Here is a copy of the output I currently get:
Please type the number inside the [] to register for a course
The number inside the () is the credit hours for the course
[1]IT1006(6)
[1]IT4782(3)
[1]IT4789(3)
[1]IT4079(6)
[1]IT2230(3)
[1]IT3345(3)
[1]IT2249(6)
Enter your choice :
I need the numbers inside the square brackets to count from 1 to 7.
This is for an academic assignment.
Your inner loop isn't doing anything. There's no point in using a loop if you've hard coded it to just run once.
I'd get rid of your outer loop and just index courses directly:
for(int i = 0; i < courses.size(); i++){
Course course = courses.get(i);
System.out.println("[" + (i+1) + "]" + course.getCode() + "(" + course.getCreditHour() + ")");
}
for(Course course : courses) means : for each course so i is reinitialised you whant a variable that will be increment on each iteration so the variable must be declared outside the block. you can write some thing like this :
int i = 1;
for(Course course : courses) {
System.out.println("[" + (i++) + "]" + course.getCode() + "(" + course.getCreditHour() + ")");
}
System.out.print("Enter your choice : ");
the method of #Carcigenicate will work too but can handle so performance issue if you use linked structure as linkedlist tthis will become for an Array :
for (int i = 0 ; i < courses.lenght ; i++){
System.out.println("[" + i + "]" + courses[i].getCode() + "(" + courses[i].getCreditHour() + ")");
}
System.out.print("Enter your choice : ");
and on collections :
for (int i = 0 ; i < courses.getSize(); i++){
System.out.println("[" + i + "]" + courses.get(i).getCode() + "(" + courses.get(i).getCreditHour() + ")");
}
System.out.print("Enter your choice : ");
Related
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 4 years ago.
It's a program that is a sports league, a group of teams plays through a Schedule of Games and determine the winner.
The program runs fine to the point where the final output won't let me see the winner, it shows this instead:
The season winner(s) with 9 points: [Ljava.lang.String;#e73f9ac
I changed it to teams.length which made the program work but it would show me the teams (i) number instead of the string name like "Vancouver".
Thanks in advance.
}
int peak = 0;
int[] total = new int[teams.length];
for (int i=0; i<teams.length; i++){
total[i] = 2*wins[i]+ties[i];
if (total[i] > peak) peak = total[i];
System.out.println(teams[i]+" - " + wins[i] + " wins, " + losses[i] + " losses, " + ties[i] + " ties = " + total[i]);
}
System.out.println("The season winner(s) with " + peak + " points: " + teams);
for (int i=0; i<teams.length; i++){
if (peak < total[i]) peak = total[i];
}
}
static int indexOfTeam(String team, String[] teams){
for (int i=0; i<teams.length; i++)
if (team.compareTo(teams[i]) == 0) return i;
return -1;
}
}
Instead of printing the winning team you're printing the teams array.
While iterating store besides the peak, the index of the winning team:
int index = -1;
for (int i=0; i<teams.length; i++){
total[i] = 2*wins[i]+ties[i];
if (total[i] > peak) {
index = i;
peak = total[i];
}
System.out.println(teams[i]+" - " + wins[i] + " wins, " + losses[i] + "
losses, " + ties[i] + " ties = " + total[i]);
}
and finally:
System.out.println("The season winner(s) with " + peak + " points: " +
teams[index]);
teams is an array of Strings, you must insert the index after the name
If you want to print all teams use Arrays.toString(teams), but I think that you would like to print only part of teams array, so you can create list of winners
List<String> winners = new ArrayList<Integer>;
for (int i=0; i<teams.length; i++){
total[i] = 2*wins[i]+ties[i];
if (total[i] > peak) {
winners.add(teams[i]);
peak = total[i];
}
System.out.println(teams[i]+" - " + wins[i] + " wins, " + losses[i] + "
losses, " + ties[i] + " ties = " + total[i]);
}
indexes object you can simply print
System.out.println("The season winner(s) with " + peak + " points: " +winners);
If you want to have an array you can use toArray() on winners object.
I'm making a random creature generator, its going all nice and dandy, however when it comes to printing the results, it prints the same result 5 times. I tried some different things like using println() multiple times and do while loops, however every time I run the file I just get a bunch of the same results. "a b c d e" are strings that generate the creature
int x = 1;
do {
System.out.println(x +" " +a +" " +b +" " +c +" " +d +" " +e);
x++;
} while (x<=5);
The reason why you're getting the same answer 5 times is because your do-while loop runs 5 times without changing the 'creatures' .
System.out.println(a +" "+ b + " " + c + " " + d + " " +e);
If you remove the do-while loop you'll get the same answer only once however just in case i misunderstood your question i made a small demo of a simple way in which to get multiple random results with a for-loop,a String-array and the Random class
String[] creatures = {"Dog", "Cat", "Fish", "Monkey", "Horse"};
Random r = new Random();
for (int i = 0; i < 5; i++) {
String creature1 = creatures[r.nextInt(creatures.length)];
String creature2 = creatures[r.nextInt(creatures.length)];
String creature3 = creatures[r.nextInt(creatures.length)];
String creature4 = creatures[r.nextInt(creatures.length)];
String creature5 = creatures[r.nextInt(creatures.length)];
System.out.println(creature1 + " " + creature2 + " " + creature3
+ " " + creature4 + " " + creature5);
}
for(int counter = 0; counter < args.length; counter++){
System.out.println("Displaying per words: " + args[counter]);
splitWords = args[counter].toCharArray();
for(int counter2 = 0; counter2 < splitWords.length; counter2++){
System.out.println("Word spliced: " + splitWords[counter2]);
System.out.println("The number equivalent of " + splitWords[counter2] + " is "
+ (int) splitWords[counter2]);
occurenceCount[(int)splitWords[counter2]]++;
System.out.println("The letter " + splitWords[counter2] +
" was shown " + occurenceCount[(int)splitWords[counter2]] + " times.");
}
}
My function doesn't detect counter2 as a variable since it was inside the nested for loop. So how do I get out of this dilemma?
I'm trying to use the argument inputs (string respectively) and post the number of occurrences using an ascii table as reference and, as you see, there's just one obstacle from stopping me from accomplishing that.
Any ideas?
Your primary problem is that you have missed one important fact - your counts are not complete until after your loop has completed.
You therefore need to print out your counts in a separate loop after your first loop is complete.
public void test() {
String[] args = {"Hello"};
int[] occurenceCount = new int[256];
for (int word = 0; word < args.length; word++) {
System.out.println("Displaying per words: " + args[word]);
char[] splitWords = args[word].toCharArray();
for (int character = 0; character < splitWords.length; character++) {
System.out.println("Word spliced: " + splitWords[character]);
System.out.println("The number equivalent of " + splitWords[character] + " is "
+ (int) splitWords[character]);
occurenceCount[(int) splitWords[character]]++;
System.out.println("Word spliced: " + splitWords[character]);
}
}
// Scond loop to print the results.
for (int character = 0; character < occurenceCount.length; character++) {
int count = occurenceCount[character];
if (count > 0) {
System.out.println("The letter " + ((char) character)
+ " was shown " + count + " times.");
}
}
}
I have a code which takes name and number from user and save those in an arraylist as object.
I am using this enhanced for loop to printout all name and number which is stored in that arraylist ...
for(Objectclass p : Test) {
System.out.println("Name: " + p.getName() + " Number: " + p.getNumber());
}
it prints like Name: blah blah Number: blah blah
now i want to add counter number before Name and number like
1.Name: blah blah Number: blah blah
2.Name ... number
3.Name ... number
... how can i add that ? if i use another for loop inside this for loop to add counter number ... it prints again and again.
Make a counter variable declared outside of the enhanced for-loop.
int i = 0;
for(Objectclass p : Test) {
System.out.println(++i + ". Name: " + p.getName() + " Number: " + p.getNumber());
}
Or so, you don't have a useless variable after it, switch back to the old method.
for(int i = 0; i < Test.size();){
Objectclass p = Test.get(i++);
System.out.println(i + ". Name: " + p.getName() + " Number: " + p.getNumber());
}
This should work:
int i = 0;
for(Objectclass p : Test)
{
i++;
System.out.println(i + ". Name: " + p.getName() + " Number: " + p.getNumber());
}
Sadly, there is no way of extracting an iteration index from an enhanced for-loop.
you could possibly try -
for(Objectclass p : Test) {
System.out.println("Index: " + Test.indexOf(p+1) + "Name: " + p.getName() + " Number: " + p.getNumber());
}
My assignment calls for the line number to be display with the output. The professor suggested I do it with a counter and as seeing Java doesn't have an easy way to print out the current line number, I just created a counter as suggested. The below code is as follows:
//Count Increment
for (count = 1; count<= 5; count++)
{
}
//Display information
System.out.println(count + "." + " " + "Street:"+ " " + streetName + " " + "#" + streetNumber);
System.out.println(count + "." + " " + "Total Rooms:"+ " " + numofRooms);
System.out.println(count + "." + " " + "Total Area:"+ " " + totalSqFt + " sq.ft");
System.out.println(count + "." + " " + "The price per Sq. Ft is " + "$" + priceperSqFt);
System.out.println(count + "." + " " + "The estimated property value is "+ "$" + estimatedPropertyvalue);
However, the output starts the line counter at six as demonstrated here:
6. Street: park avenue #44
6. Total Rooms: 5
6. Total Area: 2500.0 sq.ft
6. The price per Sq. Ft is $120.4
6. The estimated property value is $301000.0
Removing the brackets doesn't help either. How can I get the line count to correctly state 1,2,3,4,5?
Please ask for clarification if needed!! Thanks.
Your prints are outside of the for loop. Your for loop ends when the counter is "6" which is when it exits the for loop. This variable doesn't change so the current value is "6",that is why it always prints "6" below on your code. If you want to print the line number for each instruction you could do something like this:
count = 0;
System.out.println(++count + "." + " " + "Street:"+ " " + streetName + " " + "#" + streetNumber);
"++count", you increment the variable the moment you write a line, in the first case it should print 1 then 2 etc. Hope this helped :)
The loop is not required cause you are only counting the lines one time each. If you put those lines in a loop that goes from 0 to 5 you will be counting each line 5 times. Since you only need to count each line ONE time you dont need the loop and just the simple increment I previously mentioned. Hope this clears out why the loop is not required
I assume that you have somewhere above this a line defining count:
int count;
So after the for loop, you've incremented count to 6 and then started printing with count left at the last incremented value from the for loop.
So, remove the for loop and just pre-increment the count variable for each line of ouput.
int count = 0;
//Display information
System.out.println( (++count) + "." + " " + "Street:"+ " " + streetName + " " + "#" + streetNumber);
...
class Print{
static int lineno = 0;
private int static getLineNo(){
lineno = lineno + 1;
return lineno;
}
}
//Display information
System.out.println(Print.getLineNo() + "." + " " + "Street:"+ " " + streetName + " " + "#" + streetNumber);
System.out.println(Print.getLineNo() + "." + " " + "Total Rooms:"+ " " + numofRooms);
System.out.println(Print.getLineNo() + "." + " " + "Total Area:"+ " " + totalSqFt + " sq.ft");
System.out.println(Print.getLineNo() + "." + " " + "The price per Sq. Ft is " + "$" + priceperSqFt);
System.out.println(Print.getLineNo() + "." + " " + "The estimated property value is "+ "$" + estimatedPropertyv