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++;
}
Related
Here is the code, that works:
public class WorkshopApplicationMyCollection {
static void listOfPeople(List<String> someList) {
for (int i = 0; i<someList.size(); i++){
if (i == someList.size()-1) {
System.out.print(someList.get(i) + ". \n");
} else {
System.out.print(someList.get(i) + ", ");
}
}
}
public static void main(String[] args) {
List<String> listOfPeople = new ArrayList<>();
listOfAuthorities.add("Musk");
listOfAuthorities.add("Davinchie");
listOfAuthorities.add("Gates");
System.out.print("Number of people " + listOfPeople.size() + ". Those people are ");
listOfPeople(listOfAuthorities);
}
}
What I'm trying to do is to make a result of a method listOfPeople() to be a string by itself so that I could put it into the sentence. when I'm doing like this:
System.out.print("Number of people " + listOfPeople.size() + ". Those people are " + listOfPeople(listOfAuthorities));
the IDE says that the method has to not be void. How to make the method return string on it's own?
If you want to use the method in System.out.println it should return String instead of void. Think of void as a procedure that doesn't return anything. You want a method that returns String which can be used as a subject of printing out to a console.
(I prefer String.join(CharSequence delimiter, Iterable elements) to chain String elements:
static String listOfPeople(List<String> someList) {
return String.join(", ", someList) + ". \n";
}
Then it shall be used as:
System.out.print("Number of people " + listOfPeople.size() + ". Those people are " + listOfPeople(listOfPeople));
Your method should return a String, not call System.out.println directly. A common way of doing this is streaming the list and then joining it:
static String listOfPeople(List<String> someList) {
return someList.stream().collect(Collectors.joining(", ", "", ". \n"));
}
Well, a void function obviously returns nothing.
Here is a simple generic approach without using a Stream:
public static String flattenList(List<?> list)
{
StringBuilder sb = new StringBuilder();
for(int i = 0; i<list.size(); i++)
{
sb.append(list.get(i));
if(i < list.size()-1) sb.append(",");
else sb.append("\n");
}
return sb.toString();
}
If you just want to output the individual values, you can use something like that:
people.stream().forEach(System.out::println);
Use String.join("delimiter", list).
You coded wrong some name of variables, so I've corrected to you. Summarizing:
import java.util.ArrayList;
import java.util.List;
public class WorkshopApplicationMyCollection {
public static void main(String[] args) {
List<String> listOfAuthorities = new ArrayList<>();
listOfAuthorities.add("Musk");
listOfAuthorities.add("Davinchie");
listOfAuthorities.add("Gates");
System.out.print("Number of people " + listOfAuthorities.size() + ". Those people are " + String.join(" and ", listOfAuthorities));
}
}
I want a way to count the letters in an string for example:
My string : "Hello my friends "
The characters in the string : {H,e,l,o, ,m,y,f,r,i,n,d,s}
These letters exist without repeating them (with a blank space)
So the result I want is: 13
The goal of all of this is, I want to convert a string to a table of character without repeating the letters
EX: MY String = "Hello"
The table I want to get {H,e,l,o}
My attempt
public static int numberRep(String txt) {
int count = 0;
boolean v = false;
for (int i = 0; i != txt.length(); i++) {
char c = txt.charAt(i);
for (int j = i + 1; j != txt.length(); j++) {
if (txt.charAt(j) == c) {
count++;
}
}
if(count == txt.length()-1){
v = true;
}
}
if(v){
return 1 ;
}
else{
return count;
}
}
Split the string into characters and store them into a Set. A Set keeps only unique elements. The elements of the Set will be the required characters and the size of the Set will give you the count of these characters.
Do it as follows:
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.stream.Collectors;
public class Testing {
public static void main(String[] args) {
String myString = "Hello my friends ";
Set<String> set = Arrays.stream(myString.split("")).collect(Collectors.toCollection(LinkedHashSet::new));
System.out.println("Unique characters including space: " + set);
System.out.println("No. of unique characters including space: " + set.size());
}
}
Output:
Unique characters including space: [H, e, l, o, , m, y, f, r, i, n, d, s]
No. of unique characters including space: 13
What you could do is:
Create an empty list a
for character in list:
If the character is not your list a: add it to your list
This way you won't get any duplicate characters.
You can also use a set like recommended in Arvind's answer, but I think it is better for you to write a function as a task.
Set is the cleaner way to do it once you grasped the concepts of Java.
Well, this could be one of the approach to do so:
String str = "Hello my friends "
String noRepeatStr = "";
for(int i = 0; i < str.length; i++) {
if(noRepeatStr.indexOf(str[i]) == -1) // check if a char already exist, if not exist then return -1
noRepeatStr = noRepeatStr+str[i]; // add new char
}
System.out.println("Letters: " + noRepeatStr.toCharArray())
System.out.println("No of letters: " + noRepeatStr.length)
public static void main(String[] args) {
final String test = "Hello my friends";
final int size = IntStream.range(0, test.length())
.mapToObj(test::charAt)
.collect(Collectors.toSet()).size();
System.out.println(size);
}
What I've done here is iterated over all of the characters in the input string, mapped them to a char object and then collected them into a Set - instead of keeping the raw Set I've used .size() in order to get the output that you were expecting.
I haven't been able to find any questions similar to my situation so I hope I'm not missing something.
I have an array of strings. I want to print every 3 strings on their own line with commas and spacing.
Here is my method:
public static void Modify(String stringSearch)
{
ArrayList<String> records = new ArrayList<String>();
try {
File file = new File("Temp.txt");
input = new Scanner(file);
}
catch (IOException ioe) {
ioe.printStackTrace();
}
if (input.hasNext()) {
while (input.hasNext())
{
String firstName = input.next();
String lastName = input.next();
String phoneNumber = input.next();
if ((Objects.equals(firstName, stringSearch)) || (Objects.equals(lastName, stringSearch)) || (Objects.equals(phoneNumber, stringSearch))) {
records.add(firstName);
records.add(lastName);
records.add(phoneNumber);
}
} // end while
}
int size;
size = (records.size()) / 3;
System.out.printf("Found %d records:%n", size);
String[] Array = records.toArray(new String[0]);
for (int s = 0; s < Array.length; s++) {
System.out.printf("%s", Array[s]);
}
}
I am converting an arrayList to a string array in order to try and format it. I'm very new to java and am working on a project in a time crunch.
I need it to print exactly like this:
Found 2 records:
1) Garcia, John 505-338-2567
2) John, Joseph 212-780-3342
It is printing like this:
Found 2 records:
GarciaJohn505-338-2567JohnJoseph212-780-3342
Java is an Object-Oriented language, and you should use it.
Create a class representing your Person, with firstName, lastName, and phoneNumber as fields.
Then you create a List<Person> with 2 objects in it, and write a method for printing that list. The System.out.printf() you're already using can help output values in columns like you want.
You probably need to create you own data-structure, with a toString() method that suits your needs.
Something like:
public class PersonalCustomerData {
private String firstName;
private String lastName;
private String phoneNumber;
...
#Override
public String toString() {
return lastName + "," + " " + firstName + " " + phoneNumber;
}
}
And, as #Andreas mentioned in his answer, you also need a Collection<PersonalCustomerData>, that when you iterate over it, you print your fully formatted output:
private Collection<PersonalCustomerData> col;
// init the collection + do stuff...
public void printCustomerData() {
int lineNumber = 0;
for(PersonalCustomerData pcd : col) {
lineNumber++;
System.out.println(lineNumber + ")" + " " + pcd);
}
}
If you don't want to use object to contain your values and stick with your plan of doing. you can use this code to print it with format.
Replace this:
String[] Array = records.toArray(new String[0]);
for (int s = 0; s < Array.length; s++) {
System.out.printf("%s", Array[s]);
}
to this:
int numberOfLine = 1; // Counter of words per line
String[] Array = records.toArray(new String[0]);
for(String str : Array) {
String strSperator = "";
switch (numberOfLine) {
case 1:
strSperator = ", ";
numberOfLine++;
break;
case 2:
strSperator = " ";
numberOfLine++;
break;
case 3:
strSperator = "\n";
numberOfLine = 1;
break;
}
System.out.printf("%s%s",str,strSperator);
}
replace this line
for (int s = 0; s < Array.length; s++) {
System.out.printf("%s", Array[s]);`
to something like this. I didn't test out the code so there might be small typos or what not. I think this will do what you want.
As Andreas said, it would be better if you make a person class. It will look more organized and probably easier to understand.
int counter = 1;
System.out.print(records.get(0) + ",\t")
while (counter !=records.size())
{
if(counter %3 ==0)
System.out.println(records.get(counter));
else if(counter% 3== 1)
System.out.print(records.get(counter) + ",\t");
else
System.out.print(records.get(counter)+ "\t");
counter ++;
}
Since your first element will always be first name , 2nd element will be last name and 3rd element is the phone number, I print the first one initially then the modding and the while loop should handle everything I believe.
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.
Basically the program is pretty simple:
it takes a list of names and makes each player verse every player but only once..
So ceri would play 5 games in a row but what I want to happen is it to be random..
public class hatpicking {
public static void main(String[] args) {
String[] Names = { "Ceri", "Matthew", "Harry", "Lewis", "Kwok", "James"};
List<String> Matches = new ArrayList<String>();
for(int i = 0; i < Names.length; i++){
for(int j = i + 1; j <Names.length; j++){
if(Names[i].equals(Names[j])){
continue;
}else{
Matches.add(Names[i] + " v" Names[j]);
System.out.println(Names[i] + " v " + Names[j]);
}
}
}
}
}
I'm sure there is an easier way to randomise stuff but i'm only getting back into Programming so I need the work where ever I can...
Pretty much I want to assign:
(Names[i] + " v " Names[j]);
to the ArrayList - Matches but obviously
Matches.add(Names[i] + " v" Names[j]);
does not work, any hints?
Matches.add(Names[i] + " v" Names[j]);
should be
Matches.add(Names[i] + " v" + Names[j]);
Eran's answer is correct and will fix your bug. However, on a side note, a word about Java naming conventions. In Java, class names should always start with a capital letter, so class hatpicking should be class Hatpicking. In addition, variable names should start with a lowercase letter, so Names and Matchesshould be names and matches.
My guess is you just want to randomize the matches. So just use the existing code you have and just shuffle the output.
For for best shuffling results use see Shuffling section in this link. http://bost.ocks.org/mike/algorithms/
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class RandomMatch {
public void matchGenerator() {
List<String> availablePlayers = Arrays.asList("Ceri", "Matthew", "Harry", "Lewis", "Kwok", "James");
List<String> matches = new ArrayList<String>();
int MAX_PLAYERS = availablePlayers.size();
for(int i=0; i<MAX_PLAYERS; i++) {
String homePlayer = availablePlayers.get(i);
for(int j=i+1; j<MAX_PLAYERS; j++) {
String awayPlayer = availablePlayers.get(j);
if(!homePlayer.equals(awayPlayer)) {
String match = homePlayer + " vs. " + awayPlayer;
matches.add(match);
}
}
}
System.out.println("Match List\n");
for(String match : matches)
System.out.println(match);
shuffle(matches);
System.out.println("Shuffled Match List\n");
for(String match : matches)
System.out.println(match);
}
public void shuffle(List<String> matches) {
long seed = System.currentTimeMillis();
Collections.shuffle(matches, new Random(seed));
seed = System.currentTimeMillis();
Collections.shuffle(matches, new Random(seed));
}
public static void main(String[] args) {
RandomMatch randomMatch = new RandomMatch();
randomMatch.matchGenerator();
}
}