// Im trying to find the largest String in my ArrayList and print it out and also to include what index the largest element resides at and to print that to screen too. Im just wondering where Im going wrong.
Thanks.
import java.util.Scanner;
import java.util.ArrayList;
public class ArraylistString
{
public static void main(String [] args)
{
// Instance of Scanner class
Scanner keyboardIn = new Scanner(System.in);
// Declare an array list of Strings
ArrayList<String> Str = new ArrayList<>();
// Add names to ArrayList
Str.add("Jim Bob");
Str.add("Bobby Jones");
Str.add("Rob Stiles");
int largestString = Str.size();
int index = 0;
// Use for loop to print out elements from ArrayList
for(int i = 0; i < Str.size(); i++)
{ // Test which String is the largest
if(Str[i].size() > largestString)
{
largestString = Str[i].size();
index = i;
}
}
// Output largest String and index it was found at
System.out.println("Index " + index + " "+ Str[index] + " " + "is the largest and is size " + largestString);
}
}
You can also use java.util.Collections.max or the Stream version:
Java 8
String max = Collections.max(strings, Comparator.comparing(String::length)); // or s -> s.length()
OR
String max = strings.stream().max(comparing(String::length)).get();
Prior Java 8
String max = Collections.max(Str, new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
return o1.length() - o2.length();
}
});
Then
System.out.println("Index " + arr.indexOf(max) + " " + max + " " + "is the largest and is size " + max.length());
Please try these code . Here i am trying with get() to access the ArrayList elements, which is working correctly.
import java.util.Scanner;
import java.util.ArrayList;
class ArraylistString
{
public static void main(String args[])
{
ArrayList<String> Str = new ArrayList<String>();
Str.add("Jim Bob");
Str.add("Bobby Jones");
Str.add("Rob Stiles");
int largestString = Str.get(0).length();
int index = 0;
for(int i = 0; i < Str.size(); i++)
{
if(Str.get(i).length() > largestString)
{
largestString = Str.get(i).length();
index = i;
}
}
System.out.println("Index " + index + " "+ Str.get(index) + " " + "is the largest and is size " + largestString);
}
}
You have the correct idea, but wrong syntax. In Java, only arrays support the [] syntax. An ArrayList isn't an array, it's a class that implements the List interface, and you should use the get method to access its members. Similarly, a String doesn't have a size() method, it has a length() method.
I would set your largestString variable to your first String that you add:
int largestString = Str.get(0).length();
Then you should use the following to check for the largest String:
if(Str.get(i).length() > largestString) {
largestString = Str.get(i).length();
index = i;
}
You cannot index into an ArrayList with [] as you were trying to do.
I would also suggest better variable names. If I saw Str as a variable I would think it was a String. Maybe try strList or something like that.
From Java-8 and onwards:
List<Integer> numList = Arrays.stream(Str).map(String::length).collect(Collectors.toList());
Integer m = numList.stream().mapToInt(i->i).max().orElse(4000); //get strings with their length
int k = numList.indexOf(m); //index of String with Maximum Length
System.out.println(Str.get(k)); //get your longest string
Using Java 8:
Optional<String> op = Str.stream().sorted((e1,e2)-> e1.length() > e2.length() ? -1 :1).findFirst();
What are you getting as output?
also, the line
int largestString = Str.size()
is setting largestString as the number of elements in the array Str so that may cause errors. I would set it to 0 or even -1 as a baseline, or maybe Str[0].size() so that you can start your for loop with your first element as your baseline.
EDIT:
I didn't even realize this was Java so like what people are saying, you cannot use the [] operator as you can in most languages and you should use string.length() not str.size()
Related
I am trying to take the input and if there is an # symbol in the input then it finds the maximum of the integers before and after the # symbol. The maximum part I have no problem with but I do not know how to access and find the values before and after the # symbol.
import java.util.Scanner;
public class Max_Min {
public static void main(String[] args) {
//gets keyboard
Scanner keyboard = new Scanner(System.in);
//puts input into string
String inputString = keyboard.nextLine();
//splits string between characters
String[] splitInput = inputString.split("");
for (String s : splitInput) {
if(s.equals("#")){
//computes the maximum of the two integers before and after the #
}
}
//close keyboard
keyboard.close();
I did do a search to find something simliar (and im sure there is something) but could not find anything. If someone could help that would be great!
Try with this:
for (int i = 0; i < splitInput.length; i++){
if (splitInput[i].equals("#") && i != 0 && i != splitInput.length -1){
int max = Math.max(Integer.parseInt(splitInput[i - 1]), Integer.parseInt(splitInput[i + 1]));
}
//...
}
You could try:
String[] splitInput = inputString.split("#");
which would split your string at the #s.
Then you can do a iteration over your splitInput array and do a .length on each index.
You have written the simple for loop, with which you can only access the string, but not its index in the array. If you had the index, you could write:
int possibleMax = Integer.parseInt(splitInput[i - 1]) + Integer.parseInt(splitInput[i + 1]);
To get the index, there are two ways:
for (int i = 0; i < splitInput.length; i++) {
String s = splitInput[i];
...
}
Or:
int i = 0;
for (String s : splitInput) {
…
i++;
}
I don't like either version because both are more complicated than absolutely necessary, in terms of written code. If you would use Kotlin instead of Java, it would be:
splitInput.forEachIndexed { i, s ->
…
}
In Java this could be written:
forEachIndexed(
splitInput,
(i, s) -> …
);
The problem in Java is that the code inside the … cannot update the variables of the enclosing method. I'm not sure whether this will ever change. It would be possible but needs a lot of work by the language committee.
A simple way to do this would be
String input = "12#23";
String [] arr = input.split("#");
if (arr.length == 2) {
System.out.println("Max is "+Math.max(Integer.valueOf(arr[0]),Integer.valueOf(arr[1])));
}
I have a String array defined and read some values from a table into it:
String[][] ssRet = null;
ssRet = new String[tblRoDe.getNumRows()+1][2];
ssRet[0][0] = "AGR_NAME";
ssRet[0][1] = "TEXT";
for(int j=0; j<tblRoDe.getNumRows(); j++ )
{
tblRoDe.setRow( j );
ssRet[j+1][0] = tblRoDe.getString( "AGR_NAME" );
ssRet[j+1][1] = tblRoDe.getString( "TEXT" );
logger.debug("------- Start Entry #" + (j+1) + " -------");
logger.debug(ssRet[0][0] + ": " + ssRet[j+1][0]);
logger.debug(ssRet[0][1] + ": " + ssRet[j+1][1]);
logger.debug("------- End Entry #" + (j+1) + " -------");
}
My task now is: depending on a function param I will have to read values from a different table into the same string array (append this). There are still only two columns but I have to add more lines.
How can I achieve that?
You will have problems when you stick with arrays, as they are fix in their size.
For a more dynamic solution you will need a Collection, such as List - this grow with the data.
Arrays cannot be expanded once created.
So, there are the following solutions.
Create array of needed size. You can achieve this if you know the array size before reading the data.
create new array once you have to "expand" it and copy data from the small array to the bigger one. Then continue to fill the bigger array. You can use System.arraycopy() or implement the logic yourself
Use any implementation of java.util.List instead of array.
BTW unless this is a school exercise avoid using 2 dimensional array in this case. I'd recommend you to define your custom class with 2 fields name and text and then use 1 dimensional array or list according to your choice.
If you have a different amount of Rows, and you can't excatly say how much rows it will be you should use ArrayList instead of an array with an fixed size. To an ArrayList you can add as muchs values as you want. The Problem is, that an Array, once it is created, cant be resized.
To this List you could save Objects of your own type(to handle your data) like this:
public class TableRow {
private String agr_name;
private String text;
private int entryNr;
public TableRow(String agr_name, String text, int entryNr) {
this.agr_name = agr_name;
this.text = text;
this.entryNr = entryNr;
}
public String getAgr_name() {
return agr_name;
}
public void setAgr_name(String agr_name) {
this.agr_name = agr_name;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public int getEntryNr() {
return entryNr;
}
public void setEntryNr(int entryNr) {
this.entryNr = entryNr;
}
}
This used to your code should look like that:
ArrayList<TableRow> allRows = new ArrayList<>();
for (int j = 0; j < tblRoDe.getNumRows(); j++) {
tblRoDe.setRow(j);
TableRow trow = new TableRow(tblRoDe.getString("AGR_NAME"), tblRoDe.getString("TEXT"), j);
allRows.add(trow);
logger.debug("------- Start Entry #" + trow.getEntryNr() + " -------");
logger.debug("AGR_Name: " + trow.getAgr_name());
logger.debug("TEXT: " + trow.getText());
logger.debug("------- End Entry #" + trow.getEntryNr() + " -------");
}
Hope that helps!
You can't manipulate the array size after creating it , so Use List as it can grow and it's considered as a dynamic solution
List<List<String>> ssRet = new ArrayList<ArrayList<String>>();
List<String> temp=ArrayList<String>(); //creating temp list
temp.add("AGR_NAME");
temp.add("TEXT");
ssRet.add(temp);
for(int j=0; j<tblRoDe.getNumRows(); j++ )
{
tblRoDe.setRow( j );
temp.clear();//clear list instead of creating new one
temp.add(tblRoDe.getString("AGR_NAME"));
temp.add(tblRoDe.getString("TEXT"));
ssRet.add(temp);
}
To get the data :-
for(int i = 0 ; i < ssRet.size() ; i++){
for(int j = 0 ; j < ssRet.get(i).size() ; j++){
System.out.println("The "+(i+1) + " array data");
System.out.println(ssRet.get(i).get(j));
}
}
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 trying to make an Array that starts at an initial size, can have entries added to it. (I have to use an Array). To print the Array I have to following code :
public String printDirectory() {
int x = 0;
String print = String.format("%-15s" + "%-15s" + "%4s" + "\n", "Surname" , "Initials" , "Number");
// Sorts the array into alphabetical order
// Arrays.sort(Array);
while ( x < count ){
Scanner sc = new Scanner(Array[x]).useDelimiter("\\t");
secondName[x] = sc.next();
initials[x] = sc.next();
extension[x] = sc.next();
x++;
}
x = 0;
while ( x < count){
print += String.format("%-15s" + "%-15s" + "%4S" + "\n", secondName[x] , initials[x] , extension[x]);
x++;
}
return print + "" + Array.length;
}
Please ignore the extra Array.length, on the return statement.
Anyways this is working fine, firstly the Array reads a file which is formated like NameInitialsnumber on each line.
So I tried making a newEntry method and it causes problems when I want to print the Array. When I add a new entry, if the Array is too small, it will make the array bigger and add the entry. I made methods to make sure this worked and it does work. The following code for this method is:
public void newEntry(String surname, String in, String ext) {
if (count == Array.length) {
String entry = surname + "\t" + in + "\t" + ext;
int x = Array.length + 1;
String[] tempArray = new String[x];
System.arraycopy(Array, 0, tempArray, 0, Array.length);
Array = tempArray;
Array[count] = entry;
Arrays.sort(Array);
} else {
String entry = surname + "\t" + in + "\t" + ext;
Array[count] = entry;
Arrays.sort(Array);
}
count++;
}
The problem is when I then call the printDirectory method it has problems with sc.next(). The error message is as follows:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at ArrayDirectory.printDirectory(ArrayDirectory.java:106)
at ArrayDirectory.main(ArrayDirectory.java:165)
Im really new to coding and im not sure what is wrong. I know its something wrong with the new entry but im not sure what. Really grateful for any help. Thanks.
It seems that your other arrays secondName, initials, and extension are not large enough.
You need to make them bigger as well. Or even better, when you think a bit about it you will recognize that you do not need them at all.
Without for () loops such as
for(int j =0; j < array.length; j++)
{
}
I want to be able to check if a string contains any of the strings in an array globally. So for() loops don't work.
I have tried
int arraylength;
while(arraylength < array.length()){
arraylength++; }
if(string.contains(array[arraylength]) {}
but this returns an error.
edit:
To clear it up:
I want to do something like
if (string.contains(**code that checks all strings in an array**)
So I can check if string contains any of the strings in an array. As I have mentioned, for loops DO NOT work because I want to be able to execute the line of code above ANYWHERE in the class.
You can do it like this:
String veryHugeString = ...;
String[] words = new String[] { ... };
boolean foundAtLeastOne = false;
for (String word : words) {
if (veryHugeString.indexOf(word) > 0) {
foundAtLeastOne = true;
System.out.println("Word: " + word + " is found");
break;
}
}
System.out.println("Found at least one : " + foundAtLeastOne);
Try use lambdaj (download here,website) and hamcrest (download here,website), this libraries are very powerfull for managing collections, the following code is very simple and works perfectly:
import static ch.lambdaj.Lambda.having;
import static ch.lambdaj.Lambda.on;
import static ch.lambdaj.Lambda.select;
import static org.hamcrest.Matchers.containsString;
import java.util.Arrays;
import java.util.List;
public class Test2 {
public static void main(String[] args) {
List<String> list = Arrays.asList("A","BB","DCA","D","x");
String strTofind = "C";
System.out.println("List: " + list.toString());
boolean match = select(list, having(on(String.class), containsString(strTofind))).size()>0;
System.out.println("The string " + strTofind + (!match?" not":"") + " exists");
strTofind = "X";
match = select(list, having(on(String.class), containsString(strTofind))).size()>0;
System.out.println("The string " + strTofind + (!match?" not":"") + " exists");
}
}
This shows:
List: [A, BB, DCA, D, x]
The string C exists
The string X not exists
Basically, in one line you can search the string is in any strinf of the array:
boolean match = select(list, having(on(String.class), containsString(strTofind))).size()>0;
With this libraries you can solve your problem in one line. You must add to your project: hamcrest-all-1.3.jar and lambdaj-2.4.jar Hope this will be useful.
Note: in my example i use a List then if you want use an array: Arrays.asList(array) (array is string[])
For loop:
for (String search : array) {
if (message.contains(search)) {
return true;
}
}
return false;
Lambdas:
return Arrays.stream(array).anyMatch(message::contains);
Give this a try
String longString = "This is a string.";
String[] stringArray = new String[]{"apple", "ball", "This", "cat"};
int index = 0;
while(index <stringArray.length){
if(longString.contains(stringArray[index])){
System.out.println("found: "+stringArray[index]);
}
index++;
}