Java: Count every number in the array - java

I want to count the occurrence of every number that appears in the array. I've seen other answers, but I do not understand why my method does not work. I have an Array with random numbers:
int[] fält = new int[20]
This is what I did:
public static String statistik(int[] fält) {
String poäng[] = new String[20];
String output = "";
//Clear out the array:
for (int i = 0; i < poäng.length; i++) {
poäng[i] = "";
}
//Add a star for each time a number appears
for (int i = 0; i < fält.length; i++) {
for (int t = 0; t < fält.length; t++) {
if (fält[t] == i) {
poäng[i] += "*";
}
}
}
//Print it out
for (int i = 0; i < fält.length; i++) {
output += (i + 1) + ": " + poäng[i] + "\n";
}
JOptionPane.showMessageDialog(null, output);
return "";
}
Not all numbers get a star and it all ends up weird. Why?

You are checking if (fält[t] == i) please change it to if (fält[t] == fält[i])

This line :
output += (i + 1) + ": " + poäng[i] + "\n";
this will start to print "1 :" BUT you count from 0 that's why the output seems weird.
public static String statistik(int[] fält) {
String poäng[] = new String[fält.length];
String output = "";
//Clear out the array:
for (int i = 0; i < poäng.length; i++) {
poäng[i] = "";
}
//Add a star for each time a number appears
for (int i = 0; i < fält.length; i++) {
for (int t = 0; t < fält.length; t++) {
if (fält[t] == i) {
poäng[i] += "*";
}
}
}
//Print it out
for (int i = 0; i < fält.length; i++) {
output += i + ": " + poäng[i] + "\n";
}
System.out.println(output);
return "";
}

1)Hi, #Habbo, it is because the flat[] array only consists 0's
2) only in first iteration i value will be 0 and then it never be zero again.
if (fält[t] == i) {
poäng[i] += "*";
}
4)so poäng[i] inside this "i" will only zero and never increases
5) that is why you are having weird result

you should change the output message
from output += (i + 1) + ": " + poäng[i] + "\n";
to output += i + ": " + poäng[i] + "\n";
at all i think you could optimize your code
by sort it first this will cost 2 Loops
then loop upon the sorted array like this
int temp= fält[0];
output = temp + ": *";
for (int i = 1; i < fält.length; i++) {
if(fält[i] >temp){
temp = fält[i];
output +="\n"+ temp + ": *";
}
else{
output +="*";
}
}
you will have only 3 Loops In your Code not 4

Related

How do I create a queue after reading my file?

FileReader r = new FileReader(stackfile);
BufferedReader reader = new BufferedReader(r);
String s, line = null;
int counter = 1;
while((s = reader.readLine()) !=null) {
counter++;
System.out.println(counter + "." + s);
}
queue.createQueue();
System.out.println("Queue is empty with" + queue.isEmpty());
queue.enqueue(s);
System.out.println("This is the queue");
queue.displayQueue();
System.out.println("\n\nDequeuing now");
String newString = (String)queue.dequeue();
System.out.println("New String is: " + newString);
String[] lineComponents = newString.split(",");
for(int i = 0; i < lineComponents.length; i++) {
System.out.println("Line components is [ " + i + "]: " + lineComponents );
String[] binaryNumbers = lineComponents[i].split(";");
for(int j = 0; j < binaryNumbers.length; j++) {
System.out.println("Binary Numbers[" + j + "]:" + binaryNumbers[j]);
for(int k = 0; k < binaryNumbers[j].length(); k++) {
char c = binaryNumbers[j].charAt(k);
System.out.print("Single Binary numbers [" + k + "]: " + c);
}
}
}

How to let a for loop do my objectList printing

Hi I want to put my prints in a for-loop. how to do it? So something like
if index = 0,1,2 print.
if index = 2,3,4 print.
if index = 4,5,6 print.
Code:
ArrayList<Object> objectList = new ArrayList<Object>(res);
System.out.println("\n\nThis starts to look like calculations:");
System.out.print("\n" + objectList.get(0));
System.out.print(" "+ objectList.get(1));
System.out.print(" " + objectList.get(2) + " =");
System.out.print("\n\n" + objectList.get(2));
System.out.print(" " + objectList.get(3));
System.out.print(" " + objectList.get(4)+ " =");
System.out.print("\n\n" + objectList.get(4));
System.out.print(" " + objectList.get(5));
System.out.print(" " + objectList.get(6) + " =");
output:
This starts to look like calculations:
1 + 3432.123 =
3432.123 * 4535 =
4535 - 24.4 =
private String buildOperation(int pos){
String output;
if(pos == 0) {
output = "+";
}else if(pos == 1){
output = "*";
}else {
output = "-";
}
return output;
}
List<Object> objectList = new ArrayList(res);
for(int i = 0; i < objectList.size()-1; i++){
System.out.println(objectList.get(i) + buildOperation(i) + objectList.get(i+1) + "=");
}
Additionaly I'll use a HashMap with the operations to avoid all if/else conditions
Map<Integer,String> operations = new HashMap{}
operations.put(0,"+");
operations.put(1,"*");
operations.put(2,"-");
System.out.println(objectList.get(i) + operations.get(i) + objectList.get(i+1) + "=");
}
Final solution now the String size does not matter anymore.
ArrayList<Object> objectList = new ArrayList<Object>(res);
System.out.print("\n\nThis starts to look like calculations:");
int maxi= objectList.size();
maxi = maxi -2;
System.out.println("\n\nmaxi = " + maxi);
for (int i = 0; i < maxi; i+=2) {
System.out.println("");
System.out.println(i);
System.out.print("\n\n" + objectList.get(i));
System.out.print(" " + objectList.get(i + 1));
System.out.print(" " + objectList.get(i + 2)+ " =");

Stuck. Index out of bounds. Can't figure out why

I am trying to write a program that asks the user for a letter (R,G,B) and then after five output the result. There cannot be 2 letters in a row. I get indexoutofbounds when I enter the third letter and the double letter check does not work.
package absolutejava;
import java.util.Scanner;
import java.util.*;
public class RGB {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int count = 0;
boolean isColor = false;
String finalString = "";
int i = 0;
int j = 1;
String temp = "";
for (count = 0; count < 5;) {
System.out.println("Enter a color. Use R for red, G for green, and B for blue.");
temp = kb.nextLine();
if ((temp.equals("R") || temp.equals("G") || temp.equals("B"))) {
isColor = true;
temp += temp;
} else {
isColor = false;
System.out.println("Invald Color, please choose again");
}
if (isColor == true && j < 6 && i < 5) {
count++;
if (temp.length() > 2 && temp.length() <= 5 && finalString.substring(i, j).equals(temp.substring(i - 1, j - 1))) {
System.out.println("Two colors cannot be next to each other ");
isColor = false;
count--;
} else if (temp.length() == 5) {
finalString = finalString + temp.substring(i);
//debugging line
System.out.println("i " + i + "j " + j + "count " + count + " " + finalString + " length " + temp.length());
i++;
j++;
} else {
finalString = finalString + temp.substring(i, j);
//debugging line
System.out.println("i " + i + "j " + j + "count " + count + " " + finalString + " length " + temp.length());
i++;
j++;
}
}
}
System.out.println(finalString);
}
}
The following line is definitely wrong:
temp += temp;
You're replacing temp with the current input every iteration, so this will have no effect. Even if that wasn't the case, you'd just be adding the same string to itself - e.g. "A" would become "AA."
I assume you meant
finalString += temp;
or something to that effect.
In general, it seems like you're mixing up temp and final in a few places.
One more thing: don't explicitly compare to true and false, it's unnecessary and is generally considered poor style.

My for loop is only going through once

I wrote this code here. It is supposed to print out the iteNum.length (array) which is determined by the user input, but it only does one iteration and then it stops. I can't figure out why.
for (int i = 0; i < iteNum.length; i++) {
System.out.print("Num:" + (i+1) + " ");
for (i = 0; i < cMiles.length; i++) {
System.out.print(" (sc" + (i+1) + ":)" + cRandom[i] + " (tsc" + (i+1) + ":)" + df.format(cTimes[i]) + " ");
}
for (i = 0; i < fMiles.length; i++){
System.out.print(" (sf"+ (i+1) + ":)" + df.format(fRandom[i]) + " (tsf" + (i+1) + ":)" + df.format(fTimes[i])+ " " );
}
System.out.print("(cT:)" + df.format(cSum) + " (fT:)" + df.format(fSum));
if (cSum < fSum) {
System.out.print(" City is faster");
}
else {
System.out.print(" Freeway is faster");
}
}
You're reusing the same i variable in the inner and outer loops. Use separate variables.
for (int i = 0; i < iteNum.length; i++) {
for (int j = 0; j < cMiles.length; j++) {
...
}
}
As say #John you are using same iterator variable i, instread of using another one
And also this code can be simplified
if (cSum < fSum) {
System.out.print(" City is faster");
}
else {
System.out.print(" Freeway is faster");
}
like that
System.out.print((cSum < fSum) ? " City is faster" : " Freeway is faster");
On my opinion ternary operator more clear.

Array of string from the console

I have a task:
"Send integers n [1 .. 10] from command line. Enter n rows to the Console, find the shortest and the longest line. Print the results and line length."
My idea is: Create array of strings and copy every line from BufferedReader to the array data[i]. Sample of my code:
String[] data = new String[n];
int j=0;
for (int i = 1; i <= n; i++) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please, enter " + i + " string: ");
String line = in.readLine();
for (int j=0; j<=data.length;j++){
data[j] = line;
j++;
} ///:~
System.out.println("Your " + i + " string : " + data[j] + "String len: " + line.length());
} ///:~
But I could not find the way how to fill elements of array data[i] with new line from console.
Can you please give me a small hint?
To fill data, just replace the inner for-loop with a simple assignment using index i-1:
for (int i = 1; i <= n; i++) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please, enter " + i + " string: ");
String line = in.readLine();
data[i-1] = line;
System.out.println("Your " + i + " string : " + data[i-1] + "\nString len: " + line.length());
}
I left the loop from 1 to n instead of 0 to n-1 because you're printing i.
But if you only want the shortest and longest lines, there's no need to store all the lines, you only need to check the length of the current line against the length of the shortest and longest lines and change them appropriately.
the easyst way is
data[i-1] = in.readLine();
Thank you all for all your Help :)
Here is my example:
package taskstring;
import java.io.*;
public class TaskString {
public static void main(String[] args) throws java.lang.Exception {
int n = Integer.parseInt(args[0]);
if (n <= 0) {
System.out.println("Wrong! please send more numbers to java");
return;
}
System.out.println("Enjoy! You are going to send " + n + " string(s) to java");
int maxLen = 0;
int minLen = 0;
for (int i = 1; i <= n; i++) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please, enter " + i + " string: ");
String line = in.readLine();
System.out.println("Your " + i + " string : " + "String len: " + line.length());
if (maxLen < line.length()) {
System.out.println("New string is bigger");
maxLen = line.length();
} else {
System.out.println("New string is smaller");
}
if (minLen > line.length() || minLen == 0) {
System.out.println("New string is smaller" + " minLen=" + minLen);
minLen = line.length();
} else {
System.out.println("New string is bigger");
}
//return;
} ///:~
System.out.println("Max row: " + maxLen + "\nMin row: " + minLen);
} ///:~
}

Categories

Resources