I get this error message when i try to run my program
error: incompatible types
epost = split[3];
^
required: String[]
found: String
here is my code:
String [] split = ordre.split(" ");
String [] epostadr;
while(split >= 3) {
String [] epostadr = split[3];
}
I want to save the epostadr in split[3] but it wont let me do that because split only saves Strings while epostadr is a String [], what can i do to change this?
Any help would be greatly appreciated.
String [] epostadr = split[3];
split[3] is of type String while epostadr is of type String[]
Maybe you want to declare epostadr as String? [not sure I am following what you are trying to achieve]
First off, you don't have an array:
String [] epostadr;
This declares a variable than can have an array reference assigned to it.
Then you have:
String [] epostadr = split[3];
This makes no sense. split[3] is a String; you can't assign that to a variable declared as a String array.
If you need epostadr to be an array, you need to create one, assign it, then put the String in a specific location:
String [] epostadr = new String[maxNumberOfStrings];
...
epostadr[index] = split[3];
Edit: this is ignoring that the rest of your code doesn't actually do what you think it does. Your while loop (if it were written correctly) will loop forever; split.length is never going to change. Given these issues you may well want to invest in a beginner's guide to Java/programming, or at the very least go through the Java tutorials available on Oracle's website.
When you use split on a String, it makes it into a String[] so you got that right when making split as a String[]. However, in each array slot, there is a String. You are basically trying to making epostadr, which you declared as a String[], a String and that's where the incompatible types come from. A String[] can't be a String.
It's hard to know exactly what you're trying to do from this code so I'll go through and let you know what's happeneing. It looks like you're trying to take a string stored in the variable ordre, and split it so that each word has it's own index in a string array called split.
So if ordre contained the string "My name is Jones."
String [] split = ordre.split(" ");
That line would create an array named split containing the following values {My, name, is, Jones}
Here is the part that maybe you can clarify, it looks like you want those values to be in the string array epostadr, or maybe just the 3rd index which in this case would be "Jones" since indexes start with 0.
Putting the values in epostadr would be redundant since split already contains those values. But if you really wanted to copy it you could do this.
String [] epostadre = split;
If you wanted just the 3rd index, epostadre can't be a string array, but must be declared as a string and you would do this...
String epostadre = split[3];
Here you're declaring a String, which will hold one value, and setting it equal to the string that is contained in the 3rd index of split, which is Jones. split[0] = "My" split[1] = "name" and so on.
I hope that helps, let me know if you need more clarification.
Related
I have a string which is :
1|name|lastname|email|tel \n
2|name|lastname|email|tel \n
I know that I have to use a loop to display all lines but the problem is that in my assignment
I can't use arrays or other classes than String and System.
Also I would like to sort names by ascending order without using sort method or arrays.
Do I have to use compareTo method to compare two names ?
If that's the case, how do I use compareTo method to sort names.
For example, if compareTo returns 1, that means that the name is greater than the other one. In that case how do I manage the return to sort name properly in the string ?
To display all substrings of the string as in the example, you can just go through all characters one by one and store them in a string. Whenever you hit a delimiter (e.g. | or \n), print the last string.
Here's a thread on iterating through characters of a string in Java:
What is the easiest/best/most correct way to iterate through the characters of a string in Java?
If you also need to sort the names in ascending order without an array, you will need to scan the input many times - sorting N strings takes at least N*log(N) steps. If this is a data structure question, PriorityQueue should do the trick for you - insert all substrings and then pop them out in a sorted fashion :)
building on the previous answer by StoneyKeys, since i do not have the privilege to comment, you can use a simple if statement that when the char is a delimiter, System.out.println() your previous scanned string. Then you can reset the string to an empty string in preparation for scanning the next string.
In java, there are special .equals() operators for strings and chars so when you won't be using == to check strings or char. Do look into that. To reset the value of string just assign it a new value. This is because the original variable points at a certain string ie "YHStan", by making it point at "", we are effectively "resetting" the string. ie scannedstr = "";
Please read the code and understand what each line of code does. The sample code and comments is only for your understanding, not a complete solution.
String str ="";
String value = "YH\nStan";
for (int i=0; i <value.length(); i++) {
char c = value.charAt(i);
String strc = Character.toString(c);
//check if its a delimiter, using a string or char .equals(), if it is print it out and reset the string
if (strc.equals("\n")) {
System.out.println(str);
str ="";
continue; // go to next iteration (you can instead use a else if to replace this)
}
//if its not delimiter append to str
str = str +strc;
//this is to show you how the str is changing as we go through the loop.
System.out.println(str);
}
System.out.println(str); //print out final string result
This gives a result of:
Y
YH
YH
S
St
Sta
Stan
Stan
Take user input for 5 times, store them in a variable and display all 5 values in last. How can I do this in Java? Without using arrays, collections or database. Only single variable like String and int.
Output should look like this
https://drive.google.com/file/d/0B1OL94dWwAF4cDVyWG91SVZjRk0/view?pli=1
This seems like a needless exercise in futility, but I digress...
If you want to store them in a single string, you can do it like so:
Scanner in = new Scanner(System.in);
String storageString = "";
while(in.hasNext()){
storageString += in.next() + ";";
}
if you then input foo bar baz storageString will contain foo;bar;baz;. (in.next() will read the input strings to the spaces, and in.hasNext() returns false at the end of the line)
As more strings are input, they are appended to the storageString variable. To retrieve the strings, you can use String.split(String regex). Using this is done like so:
String[] strings = storageString.split(";");
the strings array which is retrieved here from the storageString variable above should have the value ["foo", "bar", "baz"].
I hope this helps. Using a string as storage is not optimal because JVM creates a new object every time a string is appended onto it. To get around this, use StringBuilder.
*EDIT: I originally had said the value of the strings array would be ["foo", "bar", "baz", ""]. This is wrong. The javadoc states 'Trailing empty strings are therefore not included in the resulting array'.
public static void main(String[] args) {
String s = "";
Scanner in = new Scanner(System.in);
for(int i=0;i<5;i++){
s += in.nextLine();
}
System.out.println(s);
}
Why dont you use Stingbuilder or StringBuffer, keep appending the some delimiter followed by the input text.
Use simple String object and concatenate it with new value provided by user.
String myString = "";
// while reading from input
myString += providedValue;
I did read the documentaion on String.split(delimiter) and it says that the return type is String[]. But I don't know how to take that return of String.split() and assign its elements to my receiving String[]. The simple-minded
String[] z = stuff.split(" ");
(where stuff is a String) does not work. It compiles fine, but the z ends up being some mumbo-jumbo with ampersands. Looks like toString of something, not like a String array. Please enlighten me. Thanks.
UPADTE: Sorry for asking this. Of course it works. I knew too little at the time and was overwhelmed.
Of course a String array contains a toString method witch is what was probably called ...
From the comments by the OP:
Sorry, I made a mistake in the original question. The corrected question is shown now. No, String[] z = stuff.split(" "); does not work. System.out.println(" z = "+z); gives z = [Ljava.lang.String;#18e2b22
You should try this to print out the String array correctly:
String[] z = stuff.split(" ");
System.out.println("z = " + Arrays.toString(z));
First, the length of the of the returned array cannot be stuff.length() but count of the stuff portions delimited by given delimiter. It doesn't matter anyway because your initialized array will be discarded after assignment of new value returned by the split function. Find your string portions in z[i] strings where i < z.length ( or z.size() ).
Write a static function that takes a string as an argument and returns
the third word in the string. Call the function with the following
string:
This is my string
Print the result to the console.
New to java and having a hard time figuring this problem at (new at java). Im not sure how to approach the problem. Ive figured out how to get the results with an array but is an array even a possible answer? What im having trouble with most is the returning of the 3rd word of the string.
edit:
Heres what I have currently to figure what was asked for, just not sure if its correct
public class problem4 {
public static void main(String[] args) {
String[] str;
str = strArray();
System.out.println(str[2]);
}
public static String[] strArray(){
String[] array = {"This", "is", "my", "string"};
return array;
}
}
This is on the right track, but its not exactly what the problem is asking for.
You are missing two big things here. First, you need to put this into a static function that takes a string (meaning you have to make your own, you cant use main). That would look something like this -
public static String getThirdWord(String s){
Second, your logic works assuming you get a String array. The problem though states you are getting a String. That means you have to do some work before you can use your (mostly correct) array notation. Here is what you need
String[] words = s.split(" ");
This will take the input, and 'split' it into parts around the spaces. You are essentially getting back an array of the individual words.
Then you can start using the array notation -
return words[2];
HOWEVER: you might get an input that is less than three words! This would cause an exception to be thrown when you do words[2]. Your problem does not state what to do in such a case, but you will almost certinally need to check the size by doing if(words.size>2)
I don't know what's happening with my code. I can't seem to figure out why an array is giving me this error. The line is String line[] = aryLines[]; specifically aryLines[];
My Code:
public void interpretGpl(String aryLines){
System.out.println("Interpreting");
String line[] = aryLines[];
String tempString[] = null;
int tempInt[] = null;
int i = interCount;
boolean isInt;
boolean storeValue = false;
I assume that aryLines is a String that contains lines of text separated by linefeeds. Here's the code you need for that:
public void interpretGpl(String aryLines) {
String line[] = aryLines.split("\n");
What are you even trying to do here? Do you want line to be an array with only the string aryLines in it? In that case:
String line[] = {aryLines};
is what you need to do.
aryLines[]
by itself kind of means nothing. [] is used only in conjunction with datatypes to represent an array of that datatype. aryLines isn't a datatype, it is the data.
aryLines is declared as a String. It is not an array. Contrariwise, line is an array. It is not a String. The thing on the right side of the = operator has to be assignable to the thing on the left side of the = operator, and Strings and arrays are completely different things.
It could be that you've chosen the wrong type for one of these variables and you wanted them to both be Strings, or both be arrays of Strings.
If the types are correct, you'll have to figure out what you wanted aryLines[] to do, and how to do it.