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 9 years ago.
Improve this question
This is simple code which should demonstrate point of my question.I don't know if there are some more effective implementations of arrays than this one.What makes them so uncomfortable to me is that we have to write condition into if() block for each element and that makes code much longer.Is there any way how to include all elements of certain array in one line? Thank you!
public class test{
static String[] text;
public static void main(String args[]){
text=new String[5];
text[0]="hello";
...
text[4]="bye";
if(text[0].contains("something")==true||...text[4].contains("something")==true)
//do something
}
}
Either use a loop:
for (String item: text) {
if (item.contains("something")) {
// TODO condition
}
}
... or use an ugly workaround, such as:
if (Arrays.toString(text).contains("something")) {
// TODO condition
}
You can write your own method to do that:
public static anyContain(String[] array, CharSequence sub) {
for (String s : array)
if (s.contains(sub))
return true;
return false;
}
Then the if-statement will be
if (anyContain(text, "something")) {
...
}
I think this is the best way (only for full equals of elements):
text=new String[5];
...
if (Arrays.asList(text).contains("something")) {
// you code here
}
If you need test for contains you can also do:
String[] test = new String[] {"one", "two", "something", "three"};
Arrays.sort(test);
int index = Arrays.binarySearch(test, "something", new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
return o1.contains(o2) ? 0 : -1;
}
});
As result you also get an index of element in array. Or negative value if not found.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
so sorry if my question is dumb but i haven't done java in 2 years. I'm working in my hw right now and i'm one method away from being done. but one of my constructor is wrong and idk where. thanks in advance!
the value variable is a private integer.
so far i have:
public FancyInt(String a) {
value = "";
a = this.value;
}
basically this constructor takes a string and initalizes the value to the appropriate int
Firstly if you want to equal "value" TO "a", you must write:
this.value = a;
in Java (and a lot of programming languages), you must write variable that you change before equal mark.
Second, if you will make "value" Integer. You must change it to int first:
try {
this.value = Integer.parseInt(a);
} catch (NumberFormatException e) {
e.printStackTrace();
}
Third, if "value" is an Integer. You must define that with numbers:
value = ""; //if value is an Integer, delete this line.
If you say that the variable "value" is a Integer, then your code cannot compile because you are assigning a String (in this case, an empty string "") to a Integer.
According to your last sentence, I think your code should look like this:
public FancyInt(String a) {
this.value = isInteger(a)? Integer.parseInt(a) : 0;
}
private boolean isInteger(String val) {
try{
Integer.parseInt(val);
return true;
}
catch (NumberFormatException e) {
return false;
}
}
You can change the implementation of the isInteger method, in this link Determine if a String is an Integer in Java you have multiple options that could help you.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
public class Reverse {
public static void main(String [] args){
System.out.println(reverse(array));
String[] array = {"I","L","O","V","E","Y","O","U"};
}
public static String reverse(String phrase){
for(int i = phrase.length()-1; i >= 0; i--){
System.out.println(phrase.charAt(i));
}//end of loop
return phrase;
}//end of second class
}//end of reverse class
There were a fair few issues with the code you posted
Method return type was incorrect, you expected String but the return value is String[]
Parameter argument incorrect, as above
phrase.length() => phrase.length
I suggest, for a better understanding, to go here, and read the documentation of all of the methods you tried to use on the array.
Here is your code, working as I assume you'd expect it to:
public class Reverse
{
public static void main(String[] args)
{
String[] array = { "I", "L", "O", "V", "E", "Y", "O", "U" };
System.out.println(reverse(array));
}
public static String[] reverse(String[] phrase)
{
for(int i = phrase.length - 1; i >= 0; i--)
{
System.out.println(phrase[i]);
}
return phrase;
}
}
There are logical mistakes in your code. I am not going to tell you the solution but rather point out few things:
In main, you have to create string first and then pass it to your reverse method. String not an array, because your reverse method takes String as parameter.
In reverse method, you probably don't want to print reversed text, but rather create new string and return it. You will then print it in main.
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 6 years ago.
Improve this question
How do I make sure that some how it doesn't throw exception at first time while checking condition with 1 and allow to check all the condition and then throws the exception related to first Condition that "Number is already added".
class Hello
{
List<Integer> newExample=new Arraylist<Integer>();
List<Integer> example=new Arraylist<Integer>();
example.add(1);
example.add(2);
example.add(3);
public void addExample()
{
for(Integer ex: example)
{
pl.adding(ex);
}
}
public void adding(Integer example)
{
if(example==1)//some work around so that rest of list of example (2,3) get chance to execute.
{
throw new NumberAlreadyAddedException("Number is already added")
}
newExample.add(example);
}
}
I believe in your case you should be checking for duplicate input at the point in time where you are receiving/adding the values to the list. I have slightly modified your code to do the check for a duplicate at the point where you are about to add the value to the List and if the value is found to be a duplicate, thrown an error immediately:
import java.util.*;
class Hello{
List<Example> exam = new ArrayList<Example>();
public void execute() throws Exception{
add(1);
add(2);
add(3);
add(1);
for(Example ex:exam){
test(ex)
}
}
public void add(Integer value) throws IllegalArgumentException{
if(exam.contains(value)){
throw new IllegalArgumentException("Number is already added.");
}
exam.add(value);
}
public void test(Example example){
System.out.println("Running test on Example: " + example);//pl.test(ex);
}
public static void main(String[] args){
Hello hello = new Hello();
hello.add(1);
hello.add(2);
hello.add(3);
hello.add(1);
}
}
class Example{}
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 8 years ago.
Improve this question
In my application I have a method fetchJSONChild() as below:
public List<String[]> fetchJSONChild(){
final List<String> child;// = new ArrayList<String>();
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
String data1 = "1,2,3";
//String[] parts = new String[3];
child = new ArrayList<String>(Arrays.asList(data1.split(",")));
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
return child;
}
In this method I have created a list and put splitted string items on it but when I return this list, I am getting an error at this line return child; as below:
Change method return type to List<String>
How can I resolve it?
Thanks
As mentioned by others you have to change List<String[]> to List<String>. You can't assign a new ArrayList to child because you declared it to be final. Besides that your code is really messed up and your Thread makes no sense. You should instead do something like this:
// Don't use a thread in your method.
public List<String> fetchJSONChild(){
final String data1 = "1,2,3";
final List<String> child = new ArrayList<String>(Arrays.asList(data1.split(",")));
return child;
}
// Call your method in a thread elsewhere
new Thread(new Runnable() {
#Override
public void run() {
// Since the method is not static, you need a reference to an object which declares this method.
final List<String> chils = yourObject.fetchJSONChild();
// Do something with your list
}
}).start();
Change:
public List<String[]> fetchJSONChild(){
to:
public List<String> fetchJSONChild(){
You're trying to return an ArrayList<String> but the return type of your method is List<String[]>. Notice the [], your method wants to return a list of arrays of strings, which is different from a list of strings.
Just change your return type to List<String>:
public List<String> fetchJSONChild()
Return type should be List<String> That's it
You've defined in your Signature a List<String[]>, so a list of String arrays.
But the List you instantiate is actually a List of Strings.
Please not that an ArrayList actually doesn't mean that it contains Arrays. (See https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html)
Either you change your method signature to public List<String> fetchJSONChild()
or you have to create Arrays of Strings within your method.
Best Regards
Datatype of child is List<String>. However return type of function is List<String[]> causing type mismatch.
Change return type of function to List<String> (and not List<String[]>) and it may work.
There is no point in having a multithreaded design for this program. Most likely when you fix the compilation problems that others mentioned your method will always return an empty List. I would suggest not to do any mutithreading in this case.
This question already has answers here:
Test if a string contains any of the strings from an array
(15 answers)
Closed 8 years ago.
how would you simplify all these conditions?
String s = "The wold is big"
if(s.contains("is") || s.contains("are") || s.contains("was") || s.contains("were"))
{
return s;
}
Since I have to check several cases like those, is there a way to simplify all those conditions?
I would write a utility method for that:
public static boolean containsAny(String s, String... words) {
for (String word : words) {
if (s.contains(word))
return true;
}
return false;
}
And now:
if (containsAny(s, "is", "are", "was", "were")) {...}
Java 8 alternative:
if (Arrays.asList("is", "are", "was", "were").stream().anyMatch(s::contains)) {...}
You can use regex for this using the matches method of the String
sample:
String s = "The wold is big";
if (s.matches("(.*)(is|are|was|were)(.*)")) {
System.out.println("lawl");
}
There is not realy a quicker way to do it. Only if you have a lot of them it would be cleaner to put them in an array and walk over the array.
Also answered here:
Test if a string contains any of the strings from an array
You can pass an array of value to check :
public boolean Contains(String[] list, String elem) {
for (String s: list){
if(elem.contains(s)) {
return true;
}
}
return false;
}
String s = "The wold is big"
String[] conditions = {"is","are","was","were"};
if(Contains(conditions,s))
{
return s;
}