I am working on a small program for school where i need to input an array. Every element in the array must be checked if the neighbours are smaller than the Element. If the neighbours are smaller --> This elements get an extra *
But i got problems with the boundaries, for example the first one and the last one. The first one has only one neighbour.
public class Tops {
Scanner sc = new Scanner(System.in);
public void calculate(){
String number;
ArrayList<String> numbers; //def’s, decl’s ArrayList
ArrayList<String> after;
numbers = new ArrayList<>(); //creates numbers
after = new ArrayList<>();
number = sc.next();
while (!"0".equals(number)) {
numbers.add(number); //initializes each ArrayList element
number = sc.next();
}
for (int i = 0; i < numbers.size(); i++) {
if (Integer.parseInt(numbers.get(i)) > Integer.parseInt(numbers.get(i+1)) && Integer.parseInt(numbers.get(i)) > Integer.parseInt(numbers.get(i-1)) ){
String replace = numbers.get(i)+"*";
after.add(replace);
} else {
after.add(numbers.get(i));
}
}
for(int i=0;i<after.size();i++){
System.out.print(after.get(i)+ " ");
}
}
public static void main(String[] args) {
new Tops().calculate();
}
}
i hope you can help me
Since you need both neighbours of an element to be smaller to add an "*", you can skip the first and the last elements (because they are missing one of the neighbours).
Adapting your code with this consideration:
import java.util.ArrayList;
import java.util.Scanner;
public class Tops {
private static final Scanner INPUT_SCANNER = new Scanner(System.in);
public static void calculate() {
// Initialize numbers
ArrayList<String> numbers = new ArrayList<>();
String number = INPUT_SCANNER.next();
while (!"0".equals(number)) {
numbers.add(number);
number = INPUT_SCANNER.next();
}
// Check the neighbours
ArrayList<String> after = new ArrayList<>();
// Check first element
if (numbers.get(0) > numbers.get(1)) {
after.add(numbers.get(0) + "*");
} else {
after.add(numbers.get(0));
}
// Check other elements
for (int i = 1; i < numbers.size() - 1; i++) {
int previous = Integer.parseInt(numbers.get(i - 1));
int current = Integer.parseInt(numbers.get(i));
int next = Integer.parseInt(numbers.get(i + 1));
String newElement = numbers.get(i);
if (current > next && current > previous) {
newElement = newElement + "*";
}
after.add(newElement);
}
// Check last element
if (numbers.get(numbers.size() - 1) > numbers.get(numbers.size() - 2)) {
after.add(numbers.get(numbers.size() - 1) + "*");
} else {
after.add(numbers.get(numbers.size() - 1));
}
after.add(numbers.get(numbers.size() - 1));
// Show the result
for (int i = 0; i < after.size(); i++) {
System.out.print(after.get(i) + " ");
}
}
public static void main(String[] args) {
calculate();
}
}
Execution example:
INPUT: 1 2 3 2 1 0
OUTPUT: 1 2 3* 2 1
Notice that:
I have made your calculate method static since you do not have any non-static field on the Tops class
I have moved the numbers initialization to the begining of the method
The final numbers are added on the after list only once so you do not need to initialize it
To perform the comparison without converting the current number from string to int twice per loop iteration, I have moved the int formats out of the if comparison.
Related
I need to create an algorithm for String decomposition.
Some examples:
ABCABCDEDEDEF --> ABC*2+DE*3+F
ABCcABCczcz --> ABC*2+cz*2+c
test --> test
Each segment of the string should be seperated by a + and, if repeated, followed up by a * plus the number of times it appears in succession.
This is what I have tried:
private static int[] prefixFunction(String source) {
int n = source.length();
int[] pi = new int[n];
for (int i = 1; i < n; i++) {
int j = pi[i - 1];
while (j > 0 && source.charAt(i) != source.charAt(j))
j = pi[j - 1];
if (source.charAt(i) == source.charAt(j))
j++;
pi[i] = j;
}
return pi;
}
This solution keeps everything in order, meaning an input like ABCABCDEDEDEF will return ABC*2+DE*3+F or an input like abDEDEab will return ab+DE*2+ab.
If you don't keep the order, it will be impossible to reconstruct the String later with 100 % accuracy.
public static void main(String[] args) {
String input = "ABCABCDEDEDEF";
String output = findDecomposition(input);
System.out.println("Output: " + output);
}
public static String findDecomposition(String input) {
String substring = input;
StringBuilder builder = new StringBuilder();
for (int start = 0, count = 1; start < input.length(); start++, count = 1) {
for (int end = start + 1; end < input.length(); end++) {
substring = input.substring(start, end);
while (true) {
String next = input.substring(start + substring.length(), Math.min(end + substring.length(), input.length()));
if (next.equals(substring)) {
count++;
start += substring.length();
end += substring.length();
} else
break;
}
if (count > 1) {
start += substring.length() - 1;
break;
}
}
if (count > 1) {
if (builder.length() > 0 && builder.charAt(builder.length() - 1) != '+')
builder.append('+');
builder.append(substring + "*" + count + "+");
} else
builder.append(input.charAt(start));
}
String result = builder.toString();
if (result.endsWith("+"))
return result.substring(0, result.length() - 1);
else
return result;
}
THe brute force alghoritm can work as follows.
Prerequisities:
First letter is set as root
Data structure of each possible solution is linked list. Value of each node is text to be written.
When outputting solution, first put to Map all text values together with number of appereances. If it appears more than once, use * as multiplicator
Example: One of the solution looks like this ABC-C-ABC, the output will be ABC*2+C
Solution:
Take next letter from input
New solutions are based on existing solutions. Each new solution is old solution + new letter added in one of the existing nodes or as single letter in new node.
Save new solutions as existing solutions.
Repeat from 1 until you process all letters
Calculate value of all solutions and select one with lowest string characters
I added example, as you can see the number of solutions are increasing quickly so it is not fully finished for all 6 letters. Each step represent the cycle from 1. to 4., you can see that in each step the previous solutions are used as base for new solutions. There are multiple new solutions created for each existing solution.
This code returns the following compositions:
ABCABCDEDEDEF -> ABC*2+DE*3+F
ABCcABCczcz -> ABCc*2+zcz
cefABCcABCczcz -> cef+ABCc*2+zcz
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class Decomposition {
public static void main(String[] args) {
Decomposition d = new Decomposition("ABCABCDEDEDEF");
System.out.println(d.getOptimalDecomposition());// Output: ABC*2+DE*3+F
d = new Decomposition("ABCcABCczcz");
System.out.println(d.getOptimalDecomposition());// Output: ABCc*2+zcz
d = new Decomposition("cefABCcABCczcz");
System.out.println(d.getOptimalDecomposition());// Output: cef+ABCc*2+zcz
}
private List> decompositions;
private String toDecompose;
public Decomposition(String toDecompose) {
decompositions = new ArrayList();
this.toDecompose = toDecompose;
}
public String getOptimalDecomposition() {
decompose(0, new ArrayList());
return calculateOptimal(convertToPartsMap());
}
private String calculateOptimal(List> partsCount) {
Collections.sort(partsCount, new SortDecompositions());
StringBuilder optimal = new StringBuilder();
for (int i = 0; i 1) {
optimal.append("*");
optimal.append(pc.count);
}
if (i != partsCount.get(0).size() - 1) {
optimal.append("+");
}
}
return optimal.toString();
}
private List> convertToPartsMap() {
List> partsMap = new ArrayList();
for (List parts : decompositions) {
List partsCount = new ArrayList();
String lastPart = null;
int curCount = 0;
for (int i = 0; i parts) {
if (nextChar == toDecompose.length()) {
decompositions.add(parts);
return;
}
char toAdd = toDecompose.charAt(nextChar);
if (parts.isEmpty()) {
parts.add("" + toAdd);
decompose(nextChar + 1, parts);
} else {
// left
List leftParts = parts.stream().collect(Collectors.toList());// shallow copy
if (!leftParts.isEmpty()) {
int last = leftParts.size() - 1;
leftParts.set(last, leftParts.get(last) + toAdd);
} else {
leftParts.add("" + toAdd);
}
// right
List rightParts = parts.stream().collect(Collectors.toList());// shallow copy
rightParts.add("" + toAdd);
decompose(nextChar + 1, leftParts);
decompose(nextChar + 1, rightParts);
}
}
}
class PartCount {
String part;
int count;
public PartCount(String part, int count) {
this.part = part;
this.count = count;
}
#Override
public String toString() {
return "[" + part + ", " + count + "]";
}
}
class SortDecompositions implements Comparator> {
public int compare(List a, List b) {
// Here you can define what exactly means "taking up least space".
return countChars(a) - countChars(b);
}
private int countChars(List listPc) {
int count = 0;
for (PartCount pc : listPc) {
count += pc.part.length();
}
return count;
}
}
This can be solved by using KMP alogorthm longest prefix which is also suffix
Steps:
iterate the string "ABCABCDEDEDEF" and construct lps array for the string. The values in the array will be
0 0 0 1 2 3 0 0 0 0 0 0 0
This lps array gives the number of times the prefix is repeated in the string.
In the above case it is repeated only one time. Considering the actual prefix number of times will be 2 it becomes ABC*2
Take the substring of the remaining string and repeat the step 1 till the end of the string.
I can provide you the code if needed. The worst time complexity will be O(n2)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Create a array of String[] S of size x in Java , add some value init , now create two more array even[] and odd[], even array shall contain the values String S[] with even index number and odd[] will contain values of String S[] with odd index number
package trying;
import java.util.Scanner;
public class ArrayTest {
public static void main(String[] args) {
int val;
int evcounter = 0;
int odcounter = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter total no of elements ");
val = sc.nextInt();
System.out.println("Enter values ");
String[] n = new String[val];
for (int i = 0; i < n.length; i++) {
n[i] = sc.next();
if (i % 2 == 0) {
evcounter++;
} else {
odcounter++;
}
if (evcounter + odcounter == val) {
String[] eve = new String[evcounter];
String[] odd = new String[odcounter];
System.out.println("******Please Help AFTER THIS**********");
}
}
}
}
Expected Output:
Enter total no of elements
3
Enter Values
HI
hello
Bye
Even array:[HI,Bye]
ODD array :[hello]
you need something like this:
public static void main(String[] args) {
int val;
int evcounter = 0;
int odcounter = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter total no of elements ");
val = sc.nextInt();
System.out.println("Enter values ");
String[] n = new String[val];
String[] eve = new String[(int) Math.ceil(val/2D)];
String[] odd = new String[val/2];
for (int i = 0; i < n.length; i++) {
n[i] = sc.next();
if (i % 2 == 0) {
eve[evcounter] = n[i];
evcounter++;
} else {
odd[odcounter] = n[i];
odcounter++;
}
}
System.out.println("Even array: " + Arrays.toString(eve));
System.out.println("Odd array: " + Arrays.toString(odd));
}
public static void main(String[] args) {
int evenCounter = 0;
int oddCounter = 0;
Scanner reader = new Scanner(System.in);
System.out.println("Enter total no of elements ");
int num = reader.nextInt();
String[] n = new String[num];
System.out.println("Enter values:");
for (int i=0;i<n.length;i++)
{
n[i]=reader.next();
if (i % 2 == 0) {
evenCounter++;
}
else
{
oddCounter++;
}
}
String[] even = new String[evenCounter];
String[] odd = new String[oddCounter];
for (int z=0;z<n.length;z++)
{
if (z%2==0)
{
for (int j=0;j<even.length;j++)
{
if (even[j]==null)
{
even[j]=n[z];
break;
}
}
}
else if (z%2==1)
{
for (int j=0;j<odd.length;j++)
{
if (odd[j]==null)
{
odd[j]=n[z];
break;
}
}
}
}
The idea is to iterate over the original String array and check if it's index is
even/odd(like you did in your code to check how many odds/evens there are).
if the index is even you go over the evens array and check for the first empty cell of the array (in java when you generate a string array you get an array full of nulls so you search for the first null and replace it with the value from the original array).
and the same about odds.
If you are using 1.8+ then better to use functional style which is much easy to understand and elegant.
import java.util.Arrays;
import java.util.function.IntPredicate;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class MyTestCase {
#Test
public void evenOddStringArrayPrinting() {
String[] src = new String[] {"HI", "Hello", "Bye"};
final String[] evenArray = getArrayFrom(src, i -> i % 2 == 0);
final String[] oddArray = getArrayFrom(src, i -> i % 2 == 1);
System.out.println(Arrays.toString(evenArray));
System.out.println(Arrays.toString(oddArray));
Assert.assertEquals(2, evenArray.length);
Assert.assertEquals(1, oddArray.length);
}
private String[] getSome(final String[] src, final IntPredicate predicate) {
return IntStream.range(0, src.length)
.filter(predicate)
.mapToObj(i -> src[i])
.collect(Collectors.toList())
.toArray(new String[] {});
}
}
This program receives 100 inputs and then outputs the lowest value. I need help checking all duplicated values inputted.
Example with 5 inputs:
5,1,1,5,4
The smallest value: 1
The amount of duplicated values: 4
import java.awt.*;
import hsa.Console;
public class ArrayNumbers
{
static Console c;
public static void main (String[] args)
{
c = new Console ();
int number[] = new int [100], i = 1, output = 0;
c.print ("Enter number #1:");
number [0] = c.readInt ();
output = number [0];
for (int count = 0 ; count < 99 ; count++)
{
c.print ("Enter number #" + (count + 2)+ ":");
number [i] = c.readInt ();
if (number [i] < output)
{
output = number [i];
}
i++;
}
c.print(output);
} // main method
} // ArrayNumbers class
It can be done by using map. Please find below code for the same:
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class MinAndDuplicates {
public static void main(String[] args) {
int number, totalDupCount=0;
Scanner stdin = new Scanner(System.in);
Map<Integer, Integer> map = new HashMap<Integer,Integer>();
//Prepare map with duplicate count for each number
for (int i = 0; i < 5; i++) {
number=stdin.nextInt();
if(map.containsKey(number)){
map.put(number, ((Integer)map.get(number)+1));
}else{
map.put(number, 1);
}
}
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
int numberCount= entry.getValue();
if (numberCount> 1) {
totalDupCount+= numberCount;
}
}
System.out.println(totalDupCount);
}
}
Hope this helps!
Below is the logic to perform your duplicate count in O(n) time and O(1) extra space.
try this
// Function to find counts of all elements present in
// arr[0..n-1]. The array elements must be range from
// 1 to n
// Traverse all array elements
int[] arr = {5,1,1,5,4};
int i = 0,n=arr.length;
int totalDupCount = 0;
while (i < n) {
// If this element is already processed,
// then nothing to do
if (arr[i] <= 0) {
i++;
continue;
}
// Find index corresponding to this element
int elementIndex = arr[i] - 1;
// If the elementIndex has an element that is not
// processed yet, then first store that element
// to arr[i] so that we don't loose anything.
if (arr[elementIndex] > 0) {
arr[i] = arr[elementIndex];
// After storing arr[elementIndex], change it
// to store initial count of 'arr[i]'
arr[elementIndex] = -1;
} else {
// If this is NOT first occurrence of arr[i],
// then increment its count.
arr[elementIndex]--;
// And initialize arr[i] as 0 means the element
// 'i+1' is not seen so far
arr[i] = 0;
i++;
}
}
System.out.println("Below are counts of all elements");
for (int j = 0; j < n; j++){
if(Math.abs(arr[j]) >= 2){
System.out.println(j + 1 + "->" + Math.abs(arr[j]));
totalDupCount +=Math.abs(arr[j]);
}
}
System.out.println("Total Duplicate Count in Array is : "+totalDupCount);
}
Output
Below are counts of all elements
1->2
5->2
Total Duplicate Count in Array is : 4
(This post is slightly uglier than my first approach, but it solves the poster's question the way they'd like it to. I have decided to put it as a separate answer.)
If you want to count the number of duplicated numbers multiple times
depending on how often they show up, you can do it with a
HashMap.
The Approach
Create a HashMap to count how often each number appears.
When reading input, increment the occurrences of that number.
To find the number of "duplicates", iterate through the HashMap and sum all of the occurrences which happen more than once.
Example
import java.util.Scanner;
import java.util.Map;
import java.util.HashMap;
public class DuplicateCounter {
static int[] numbers = new int[100];
static HashMap<Integer, Integer> occurrences = new HashMap<>();
public static void main(String[] args) {
readInput();
int duplicates = countDuplicates();
System.out.printf("%d numbers appeared multiple times.\n", duplicates);
}
public static void readInput() {
Scanner stdin = new Scanner(System.in);
for (int i = 0; i < numbers.length; i++) {
int number = stdin.nextInt();
numbers[i] = number;
incrementCount(number);
}
stdin.close();
}
public static int countDuplicates() {
int duplicates = 0;
for (Map.Entry<Integer, Integer> entry : occurrences.entrySet()) {
int numOfOccurrences = entry.getValue();
if (numOfOccurrences > 1) {
duplicates += numOfOccurrences;
}
}
return duplicates;
}
public static void incrementCount(int number) {
if (occurrences.get(number) != null) {
int previous = occurrences.get(number);
occurrences.put(number, previous + 1);
} else {
occurrences.put(number, 1);
}
}
}
After hard searchig I still haven't found the proper answer for my question and there is it:
I have to write a java program that enters an array of strings and finds in it the largest sequence of equal elements. If several sequences have the same longest length, the program should print the leftmost of them. The input strings are given as a single line, separated by a space.
For example:
if the input is: "hi yes yes yes bye",
the output should be: "yes yes yes".
And there is my source code:
public static void main(String[] args) {
System.out.println("Please enter a sequence of strings separated by spaces:");
Scanner inputStringScanner = new Scanner(System.in);
String[] strings = inputStringScanner.nextLine().split(" ");
System.out.println(String.join(" ", strings));
ArrayList<ArrayList<String>> stringsSequencesCollection = new ArrayList<ArrayList<String>>();
ArrayList<String> stringsSequences = new ArrayList<String>();
stringsSequences.add(strings[0]);
for (int i = 1; i < strings.length; i++) {
if(strings[i].equals(strings[i - 1])) {
stringsSequences.add(strings[i]);
} else {
System.out.println(stringsSequences + " " + stringsSequences.size());
stringsSequencesCollection.add(stringsSequences);
stringsSequences.clear();
stringsSequences.add(strings[i]);
//ystem.out.println("\n" + stringsSequences);
}
if(i == strings.length - 1) {
stringsSequencesCollection.add(stringsSequences);
stringsSequences.clear();
System.out.println(stringsSequences + " " + stringsSequences.size());
}
}
System.out.println(stringsSequencesCollection.size());
System.out.println(stringsSequencesCollection.get(2).size());
System.out.println();
int maximalStringSequence = Integer.MIN_VALUE;
int index = 0;
ArrayList<String> currentStringSequence = new ArrayList<String>();
for (int i = 0; i < stringsSequencesCollection.size(); i++) {
currentStringSequence = stringsSequencesCollection.get(i);
System.out.println(stringsSequencesCollection.get(i).size());
if (stringsSequencesCollection.get(i).size() > maximalStringSequence) {
maximalStringSequence = stringsSequencesCollection.get(i).size();
index = i;
//System.out.println("\n" + index);
}
}
System.out.println(String.join(" ", stringsSequencesCollection.get(index)));
I think it should be work correct but there is a problem - the sub array list's count isn't correct: All the sub arrayList's size is 1 and for this reason the output is not correct. I don't understand what is the reason for this. If anybody can help me to fix the code I will be gratefull!
I think it is fairly straight forward just keep track of a max sequence length as you go through the array building sequences.
String input = "hi yes yes yes bye";
String sa[] = input.split(" ");
int maxseqlen = 1;
String last_sample = sa[0];
String longest_seq = last_sample;
int seqlen = 1;
String seq = last_sample;
for (int i = 1; i < sa.length; i++) {
String sample = sa[i];
if (sample.equals(last_sample)) {
seqlen++;
seq += " " + sample;
if (seqlen > maxseqlen) {
longest_seq = seq;
maxseqlen = seqlen;
}
} else {
seqlen = 1;
seq = sample;
}
last_sample = sample;
}
System.out.println("longest_seq = " + longest_seq);
Lots of issues.
First of all, when dealing with the last string of the list you are not actually printing it before clearing it. Should be:
if(i == strings.length - 1)
//...
System.out.println(stringsSequences + " " + stringsSequences.size());
stringsSequences.clear();
This is the error in the output.
Secondly, and most importantly, when you do stringsSequencesCollection.add you are adding an OBJECT, i.e. a reference to the collection. When after you do stringsSequences.clear(), you empty the collection you just added too (this is because it's not making a copy, but keeping a reference!). You can verify this by printing stringsSequencesCollection after the first loop finishes: it will contain 3 empty lists.
So how do we do this? First of all, we need a more appropriate data structure. We are going to use a Map that, for each string, contains the length of its longest sequence. Since we want to manage ties too, we'll also have another map that for each string stores the leftmost ending position of the longest sequence:
Map<String, Integer> lengths= new HashMap<>();
Map<String, Integer> indexes= new HashMap<>();
String[] split = input.split(" ");
lengths.put(split[0], 1);
indexes.put(split[0], 0);
int currentLength = 1;
int maxLength = 1;
for (int i = 1; i<split.length; i++) {
String s = split[i];
if (s.equals(split[i-1])) {
currentLength++;
}
else {
currentLength = 1;
}
int oldLength = lengths.getOrDefault(s, 0);
if (currentLength > oldLength) {
lengths.put(s, currentLength);
indexes.put(s, i);
}
maxLength = Math.max(maxLength, currentLength);
}
//At this point, youll have in lengths a map from string -> maxSeqLengt, and in indexes a map from string -> indexes for the leftmost ending index of the longest sequence. Now we need to reason on those!
Now we can just scan for the strings with the longest sequences:
//Find all strings with equal maximal length sequences
Set<String> longestStrings = new HashSet<>();
for (Map.Entry<String, Integer> e: lengths.entrySet()) {
if (e.value == maxLength) {
longestStrings.add(e.key);
}
}
//Of those, search the one with minimal index
int minIndex = input.length();
String bestString = null;
for (String s: longestStrings) {
int index = indexes.get(s);
if (index < minIndex) {
bestString = s;
}
}
System.out.println(bestString);
Below code results in output as you expected:
public static void main(String[] args) {
System.out.println("Please enter a sequence of strings separated by spaces:");
Scanner inputStringScanner = new Scanner(System.in);
String[] strings = inputStringScanner.nextLine().split(" ");
System.out.println(String.join(" ", strings));
List <ArrayList<String>> stringsSequencesCollection = new ArrayList<ArrayList<String>>();
List <String> stringsSequences = new ArrayList<String>();
//stringsSequences.add(strings[0]);
boolean flag = false;
for (int i = 1; i < strings.length; i++) {
if(strings[i].equals(strings[i - 1])) {
if(flag == false){
stringsSequences.add(strings[i]);
flag= true;
}
stringsSequences.add(strings[i]);
}
}
int maximalStringSequence = Integer.MIN_VALUE;
int index = 0;
List <String> currentStringSequence = new ArrayList<String>();
for (int i = 0; i < stringsSequencesCollection.size(); i++) {
currentStringSequence = stringsSequencesCollection.get(i);
System.out.println(stringsSequencesCollection.get(i).size());
if (stringsSequencesCollection.get(i).size() > maximalStringSequence) {
maximalStringSequence = stringsSequencesCollection.get(i).size();
index = i;
//System.out.println("\n" + index);
}
}
System.out.println(stringsSequences.toString());
I am writing a program that reads through a .txt file of weather data, and among other things, keep count of various weather patterns for each day of the year.
The .txt file has 365 lines of various values (one line of values for each day of the year). Each line houses the high temp, low temp, and Weather status (formatted as a String of six 1's and 0's, with a 1 indicating that Fog/Rain/Snow/Hail/Thunder/Tornado occurred on that day). For example, the String 011000, would indicate that both rain and snow occurred.
Sample weather file looks like (line breaks for spacing):
High, Low, Weather String:
45, 32.4, 100000
43.2, 35, 100001
50.2, 32.1 101101
I have completed the vast majority of the program that traces through the weather.txt file and keeps track of the yearly high and yearly low, yet am having trouble tallying the weather status for each type (6 types). I realize I don't do the best in explaining, but my goal is to keep count, for all 365 formatted String values, how many 1's for each index of the String. So in looking at the sample weather file above, my end result would be [3, 0, 1, 1, 0, 2].
In the pasted method below, I pass in a String array (I created a String array previously in the program, which houses all 365 String formatted values... [100001, 100000, 101101, ...]). In this method, I created a new tally array with 6 values. I am trying to write a loop that traces through the passed in weather array (365 values), and increases the tally array index if a 1 occurs at the said index. The final tally array would look something like [101, 31, 3, 218, 42, 101]...made up numbers for sample output.
The logic is giving me a lot of trouble. Assuming I have done my bit in explaining this, can anyone offer me advice.
Note - the class constant of NUMBER_OF_WEATHER_TYPES is set to 6.
public static int[] getWeatherCounts(String[] weather) {
int[] tally = new int[6];
for (int i = 0; i < weather.length; i++) {
for (int j = 0; j < NUMBER_OF_WEATHER_TYPES; j++) {
if (weather[j].charAt(j) == 1) {
tally[j]++;
}
return tally;
}
}
return tally;
}
Whole program for context:
import java.util.*;
import java.io.*;
public class WeatherInfo {
public static final int DAYS_PER_YEAR = 365;
public static final int NUMBER_OF_WEATHER_TYPES = 6;
public static void main (String[] args) {
String firstArgs = args[0];
Scanner input = null;
if (args.length != 1) {
System.out.println("Error"); //Look more into this!!!!
} else {
try {
input = new Scanner(new File(firstArgs));
} catch (FileNotFoundException e) {
System.out.println("Error: " + e);
System.exit(1);
}
}
String lineDiscard = input.nextLine();
double[] highs = new double[DAYS_PER_YEAR];
double[] lows = new double[DAYS_PER_YEAR];
String[] weather = new String[DAYS_PER_YEAR];
for (int i = 0; i < DAYS_PER_YEAR; i++) {
input.next();
input.next();
highs[i] = input.nextDouble();
lows[i] = input.nextDouble();
weather[i] = input.next();
}
displayWeatherStatistics(highs, lows, weather);
}
public static void displayWeatherStatistics(double[] highs, double[] lows, String[] weather) {
double highTemp = Integer.MIN_VALUE;
double lowTemp = Integer.MAX_VALUE;
// for loop for highs
for (int i = 0; i < highs.length; i++) {
if (highs[i] > highTemp) {
highTemp = highs[i];
}
}
// for loop for lows
for (int i = 0; i < lows.length; i++) {
if (lows[i] < lowTemp) {
lowTemp = lows[i];
}
}
// printouts for the low and high temps of the year...need to fix this a bit
System.out.println("Highest Temp: " + highTemp + " (F)");
System.out.println("Lowest Temp: " + lowTemp + " (F)");
System.out.println(Arrays.toString(getWeatherCounts(weather)));
}
public static int[] getWeatherCounts(String[] weather) {
int[] tally = new int[6];
for (int i = 0; i < weather.length; i++) {
for (int j = 0; j < NUMBER_OF_WEATHER_TYPES; j++) {
if (weather[i].charAt(j) == 1) {
tally[j]++;
}
return tally;
}
}
return tally;
}
}
Well, it's hard to tell without seeing your whole program. But it looks to me like
if (weather[j].charAt(j) == 1) {
tally[j]++;
}
return tally;
should be
if (weather[i].charAt(j) == '1') {
tally[j]++;
}
// omit the return tally, we don't want to do that until the end