Reading in information into multiple arrays - java

The purpose of this program is to take information from a file about a music collection and turn it into three arrays.
>4
>141 Pure Heroine:Lorde
>171 Lights Out:Ingrid Michaelson
>270 Unorthodox Jukebox :Bruno Mars
>190 Head Or Heart:Christina Perri
In the file, the 4 stands for how long the arrays will be, the numbers are one array, the album titles another, and the artist names are the final array. The arrays for the titles and artist names are separated by the colon. While I can create the array for the numbers, what is giving me trouble is how to create the separate arrays for name and titles. I understand that I have to convert it into a sting and use the colon as a delimiter but I'm unsure as to how.
import java.util.*;
import java.io.*;
public class tunes {
public static void main(String[] args) throws FileNotFoundException {
int size; //Determines the size of the arrays
Scanner input = new Scanner(new File("music.txt"));
size = input.nextInt();
int[] time = new int[size];
for (int i = 0; i < time.length; i++) { // Creates an array for the numbers
time[i] = input.nextInt();
input.nextLine();
}
String[] artist = new String[size];
for (int i = 0; i <artist.length; i++) {
while (input.hasNextLine()){
}
}
System.out.println();
System.out.println("TOTAL TIME\t\t\t\t" + calcTotalTime(time));
System.out.println();
System.out.println();
System.out.println("LONGEST TRACK");
System.out.println("-------------");
System.out.println();
System.out.println();
System.out.println("SHORTEST TRACK");
System.out.println("--------------");
}
public static void printTable(int[] time, String[] artist, String[] title) {
System.out.println("TITLE\t\t\t" + "ARTIST\t\t\t " + "TIME");
System.out.println("-----\t\t\t" + "------\t\t\t " + "----");
for (int i = 0; i < time.length; i++) {
System.out.println(title[i] + "\t" + artist[i] + "\t" + time[i]);
}
}
public static int calcTotalTime(int[] time) {
int sum = 0;
for (int i = 0; i < time.length; i++) {
sum = sum + time[i];
}
return sum;
}
public static int findLongest(int[] time) {
int longest = 0;
for (int i = 1; i < time.length; i++) {
if (time[i] > time[longest]) {
longest = i;
}
}
return longest;
}
public static int findShortest(int[] time) {
int shortest = 0;
for (int i = 1; i < time.length; i++) {
if (time[i] < time[shortest]) {
shortest = i;
}
}
return shortest;
}
}
An example of how the output would look like would be
>Pure Heroine Lorde 141
>Lights Out Ingrid Michaelson 171
>Unorthodox Jukebox Bruno Mars 270
>Head or Heart Christina Perri 190

You can use String.split(":") on your text to split the artist/title Strings into String[] arrays.
For instance:
System.out.println(Arrays.toString("Head Or Heart:Christina Perri".split(":")));
Output
[Head Or Heart, Christina Perri]

Use the String split() method to save the pieces into a new array. The split() method takes a regular expression - see this question about how to use it. The colon is not a special character in a RegExp and therefore does not need to be escaped.

Allocate all the arrays first after reading the length of the arrays, then parse each line in one go using split to tokenize the artist-title part of the line.
size = input.nextInt();
int[] time = new int[size];
String[] artist = new String[size];
String[] title = new String[size];
for (int i = 0; i < time.length; i++) {
time[i] = input.nextInt();
String[] parts = input.next().split( ":" );
artist[i] = parts[0];
title[i] = parts[1];
}

Related

Java Stdin Cannot convert from String[] to String, but inputs are String?

I am doing a programming assignment that takes all of its input from stdin. The first input is an int n to tell you how many strings will follow, and the next n inputs are strings of varying lengths. The goal is to find the longest string(s) and print them.
I thought this was easy, but for the life of me, I cannot get the stdin to work with me. The eclipse arguments entered are (separated by enter):
3
a2
b3c
7
Yet I run the program, and it tells me it cannot convert from String[] to String. I do not understand how any of the above are String[]. The code is below:
import java.util.Scanner;
public class A2P1 {
public static void main(String[] args) {
int size = Integer.parseInt(args[0]);
String[] str = new String[size];
Scanner sc = new Scanner(System.in);
for (int i=0; i < size; i++) {
str[i] = sc.nextLine().split(" "); // The error
//str[i] = sc.next(); This line and the line below throw
//str[i] = sc.nextLine(); no errors, but also gives no output.
}
String[] longest = new String[size];
String[] temp = new String[size];
longest[0] = str[0];
int numToBeat = str[0].length();
int k = 0;
for (int i=0; i < size; i++) {
if (str[i].length() > numToBeat) {
numToBeat = str[i].length();
k = 0;
longest = temp;
longest[k] = str[i];
k++;
}
else if (str[i].length() == numToBeat) {
longest[k] = str[i];
}
}
System.out.println("The longest input strings are:");
for (int i=0; i < k; i++) {
System.out.println(longest[i]);
}
sc.close();
}
}
Tried:
Changing str[i] = sc.nextLine().split(" "); to its other variations in the code
Changing input values
Googling stdin for the last hour trying to find any documentation that helps me
If you are using eclipse arguments separated by enter then your logic is wrong:
according to your logic get 1st element from the eclipse argument like args[0]
another Input is taken from the console.
if you need to take all elements from the eclipse argument follow the below code:
public class A2P1 {
public static void main(String[] args) {
int size = Integer.parseInt(args[0]);
String[] str = new String[size];
int length=0;
String loggestString="";
for (int i=1; i < size; i++) {
str[i] = args[i];
int strLen = str[i].length();
if(strLen>length) {
length=strLen;
loggestString=str[i];
}
}
System.out.println(loggestString);
}
}

Count each element in string array

Hey guys this is my code for splitting the array first without using any inbuilt functions. It works fine, my question is in the second part.
static String[] split(String ss) {
String[] a = new String[1];
String s = "";
for (int i = 0; i < ss.length(); i++) {
if (ss.charAt(i) == ' ') {
s += ", "
} else {
s += ss.charAt(i);
}
for (int j = 0; j < a.length; j++) {
a[j] = "[" + s + "]";
}
}
return a;
}
I need now to count each letter in a word and give it out also without inbuilt functions as split, chartoarray and so on.
this is to what i came so far.
for example String="This is just an example". it should give out
This=4
is=2
..
static String[][] LettersCount(String[] array) {
int count=0;
String [][] a =new String[array.length][array.length];
String s= "" + Arrays.toString(array);
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ' ') {
count = 0;
} else {
count++;
}
You can use property of character that it has a numerical value after all. Lets use it as index and store the counts in an array. (so we will mimic Map this way)
int[] counter = new int[256] ;// this will hold count of all letters
counter[(int) character]++; // this is how you do the counting
public class JavaArrayLengthTest {
public static void main(String[] args) {
String[] testArray = { "A", "B", "C" };
int arrayLength = testArray.length;
System.out.println("The length of the array is: " + arrayLength);
}
}

sub arraylist's size isn't correct

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());

Java words reverse

I am new to Java and I found a interesting problem which I wanted to solve. I am trying to code a program that reverses the position of each word of a string. For example, the input string = "HERE AM I", the output string will be "I AM HERE". I have got into it, but it's not working out for me. Could anyone kindly point out the error, and how to fix it, because I am really curious to know what's going wrong. Thanks!
import java.util.Scanner;
public class Count{
static Scanner sc = new Scanner(System.in);
static String in = ""; static String ar[];
void accept(){
System.out.println("Enter the string: ");
in = sc.nextLine();
}
void intArray(int words){
ar = new String[words];
}
static int Words(String in){
in = in.trim(); //Rm space
int wc = 1;
char c;
for (int i = 0; i<in.length()-1;i++){
if (in.charAt(i)==' '&&in.charAt(i+1)!=' ') wc++;
}
return wc;
}
void generate(){
char c; String w = ""; int n = 0;
for (int i = 0; i<in.length(); i++){
c = in.charAt(i);
if (c!=' '){
w += c;
}
else {
ar[n] = w; n++;
}
}
}
void printOut(){
String finale = "";
for (int i = ar.length-1; i>=0;i--){
finale = finale + (ar[i]);
}
System.out.println("Reversed words: " + finale);
}
public static void main(String[] args){
Count a = new Count();
a.accept();
int words = Words(in);
a.intArray(words);
a.generate();
a.printOut();
}
}
Got it. Here is my code that implements split and reverse from scratch.
The split function is implemented through iterating through the string, and keeping track of start and end indexes. Once one of the indexes in the string is equivalent to a " ", the program sets the end index to the element behind the space, and adds the previous substring to an ArrayList, then creating a new start index to begin with.
Reverse is very straightforward - you simply iterate from the end of the string to the first element of the string.
Example:
Input: df gf sd
Output: sd gf df
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
public class Count{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter string to reverse: ");
String unreversed = scan.nextLine();
System.out.println("Reversed String: " + reverse(unreversed));
}
public static String reverse(String unreversed)
{
ArrayList<String> parts = new ArrayList<String>();
String reversed = "";
int start = 0;
int end = 0;
for (int i = 0; i < unreversed.length(); i++)
{
if (unreversed.charAt(i) == ' ')
{
end = i;
parts.add(unreversed.substring(start, end));
start = i + 1;
}
}
parts.add(unreversed.substring(start, unreversed.length()));
for (int i = parts.size()-1; i >= 0; i--)
{
reversed += parts.get(i);
reversed += " ";
}
return reversed;
}
}
There is my suggestion :
String s = " HERE AM I ";
s = s.trim();
int j = s.length() - 1;
int index = 0;
StringBuilder builder = new StringBuilder();
for (int i = j; i >= 0; i--) {
Character c = s.charAt(i);
if (c.isWhitespace(c)) {
index = i;
String r = s.substring(index+1, j+1);
j = index - 1;
builder.append(r);
builder.append(" ");
}
}
String r=s.substring(0, index);
builder.append(r);
System.out.println(builder.toString());
From adding debug output between each method call it's easy to determine that you're successfully reading the input, counting the words, and initializing the array. That means that the problem is in generate().
Problem 1 in generate() (why "HERE" is duplicated in the output): after you add w to your array (when the word is complete) you don't reset w to "", meaning every word has the previous word(s) prepended to it. This is easily seen by adding debug output (or using a debugger) to print the state of ar and w each iteration of the loop.
Problem 2 in generate() (why "I" isn't in the output): there isn't a trailing space in the string, so the condition that adds a word to the array is never met for the last word before the loop terminates at the end of the string. The easy fix is to just add ar[n] = w; after the end of the loop to cover the last word.
I would use the split function and then print from the end of the list to the front.
String[] splitString = str.split(" ");
for(int i = splitString.length() - 1; i >= 0; i--){
System.out.print(splitString[i]);
if(i != 0) System.out.print(' ');
}
Oops read your comment. Disregard this if it is not what you want.
This has a function that does the same as split, but not the predefined split function
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string : ");
String input = sc.nextLine();
// This splits the string into array of words separated with " "
String arr[] = myOwnSplit(input.trim(), ' '); // ["I", "AM", "HERE"]
// This ll contain the reverse string
String rev = "";
// Reading the array from the back
for(int i = (arr.length - 1) ; i >= 0 ; i --) {
// putting the words into the reverse string with a space to it's end
rev += (arr[i] + " ");
}
// Getting rid of the last extra space
rev.trim();
System.out.println("The reverse of the given string is : " + rev);
}
// The is my own version of the split function
public static String[] myOwnSplit(String str, char regex) {
char[] arr = str.toCharArray();
ArrayList<String> spltedArrayList = new ArrayList<String>();
String word = "";
// splitting the string based on the regex and bulding an arraylist
for(int i = 0 ; i < arr.length ; i ++) {
char c = arr[i];
if(c == regex) {
spltedArrayList.add(word);
word = "";
} else {
word += c;
}
if(i == (arr.length - 1)) {
spltedArrayList.add(word);
}
}
String[] splitedArray = new String[spltedArrayList.size()];
// Converting the arraylist to string array
for(int i = 0 ; i < spltedArrayList.size() ; i++) {
splitedArray[i] = spltedArrayList.get(i);
}
return splitedArray;
}

Disappearing Arraylist Values

I am writing a Java program that will take a sentence (or phrase) and translate it into a group of objects that the computer can easily read. I wanted to make a simple word separating program, and then extend it later on.
My code is like this:
package Literary;
import java.util.ArrayList;
public class WordParser {
public static String[] getWords(String tempone){
ArrayList<String> temptwo = new ArrayList();
ArrayList<Character> tempthree = new ArrayList();
for (int tempfour = 0; tempfour == tempone.length() - 1; tempfour++){
if (tempone.charAt(tempfour) != ' '){
tempthree.add(tempone.charAt(tempfour));
} else {
temptwo.add(getStringRepresentation(tempthree));
tempthree.clear();
}
}
String[] tempfive = new String[temptwo.size()];
for (int tempfour = 0; tempfour == tempfive.length - 1; tempfour++){
tempfive[tempfour] = temptwo.get(tempfour);
}
return tempfive;
}
/** Courtesy of Vineet Reynolds on StackExchange.
*
* "You can iterate through the list and create the string."
*
* #param list
* #return
*/
public static String getStringRepresentation(ArrayList<Character> list){
StringBuilder builder = new StringBuilder(list.size());
for(int i = 0; i == list.size() + 1; i++)
{
builder.append(list.get(i).charValue());
}
return builder.toString();
}
}
It's supposed to receive a string as an input, and return a list of strings that have been separated by spaces.
But when I run my main class:
import Literary.WordParser;
public class Start {
public static void main(String[] args) {
String x = "There was once a sword in the stone";
String[] tempstring = WordParser.getWords(x);
for (int i = 1; i == tempstring.length; i++){
System.out.println("Word " + i + " : " + tempstring[i]);
}
}
}
The console tells me nothing except run: and BUILD SUCCESSFUL (total time: 1 second).
I'm using Netbeans 8 and Java 1.7 if that helps.
Looks like the problem's here:
for (int i = 1; i == tempstring.length; i++) {
This for loop will run at most once: if tempstring is exactly one String long, it should print out the word.
However, since your test sentence has 8 words, nothing will ever print out (provided WordParser works correctly).
You probably want to change this line to: (note the < between i and tempstring.length.)
for (int i = 1; i < tempstring.length; i++) {
so that it will loop through all the items in tempstring.
You had multiple issues in your code:
1) for loops were not properly made, they would never execute. Use either !=, > or < instead of ==.
2) you don't need a method getWords() nor getStringRepresentation(). Method like that are already implemented in Java.
So the final code should be this:
public class WordParser {
public static String[] getWords(String tempone) {
return tempone.split(" ");
}
public static void main(String[] args) {
String x = "There was once a sword in the stone";
String[] tempstring = WordParser.getWords(x);
for (int i = 0; i < tempstring.length; i++) {
System.out.println("Word " + (i+1) + " : " + tempstring[i]);
}
}
}
Output:
Word 1 : There
Word 2 : was
Word 3 : once
Word 4 : a
Word 5 : sword
Word 6 : in
Word 7 : the
Word 8 : stone
I've also fixed your code that runs the same as above, if you are interested:
import java.util.ArrayList;
public class WordParser {
public static String[] getWords(String tempone) {
ArrayList<String> sarr = new ArrayList<String>();
ArrayList<Character> tempthree = new ArrayList<Character>();
String[] ansarr;
if(tempone.charAt(tempone.length()-1) != ' ')
tempone += " "; //Add white space to the end to catch the last word
for (int i = 0; i < tempone.length(); i++) {
if (tempone.charAt(i) != ' ') {
tempthree.add(tempone.charAt(i));
} else {
sarr.add(tempthree.toString());
tempthree.clear();
}
}
ansarr = new String[sarr.size()];
for (int i = 0; i < ansarr.length; i++) {
ansarr[i] = sarr.get(i);
}
return ansarr;
}
public static void main(String[] args) {
String x = "There was once a sword in the stone";
String[] tempstring = WordParser.getWords(x);
for (int i = 0; i < tempstring.length; i++) {
System.out.println("Word " + (i+1) + " : " + tempstring[i]);
}
}
}
Enjoy! :)
I think you should use String.split(" ") which seems to do the same thing
Change your main method as follows,
and it will work
public static void main(String[] args) {
String x = "There was once a sword in the stone";
String[] tempstring = WordParser.getWords(x);
for (int i = 1; i <= tempstring.length; i++){
System.out.println("Word " + i + " : " + tempstring[i - 1]);
}
}
For the WordParser you could use,
public class WordParser
{
public static String[] getWords(String tempone)
{
return tempone.split(" ");
}
}
First of, I would recommend using the split method to break up a sentence
it is defined as:
public String[] split(String regex, int limit)
and you can simply call
String s1=new String("Random words in a sentence");
String[] words=s1.split(" ");
in order to break the string up into words and you will now have a String
array of five elements where each element consists of a word
In Respect to your question, you are not using the conditional statement correctly
You want to iterate over the elements of the String array WHILE the position
is less than stringname.length, not only if it the position equals the stringname.length
Therefore, you must make the following changes in these parts of your code
For Example:
for (int i = 1; i == tempstring.length; i++)
should have its line changed to
for (int i = 1; i < tempstring.length; i++)
and this problem also occurs in various places in your WordParser.java file
It is useful to remember also that you may often want to start at index 0 instead
of index 1, as java has its' first indice as 0.

Categories