Dealing with String array elements in Java [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
So I have this particular code:
import java.util.*;
class insertWordInMiddle {
public static void main(String[] args) {
String s = "Python 3.0";
String s_split[] = s.split(" ");
String a = new String(s_split[0]);
String b = new String(s_split[1]);
String c = a + " Tutorial " + b;
System.out.println(c);
}
}
I was practising and I wanted to insert a word between two words (in the form of a string). It works, however I have yet other way of doing this but cannot get why it doesn't work:
import java.util.*;
class insertWordInMiddle {
public static void main(String[] args) {
String s = "Python 3.0";
String s_split[] = s.split(" ");
String final = s_split[0]+" Tutorial "+s_split[1];
System.out.println(final);
}
}
Error:
/home/reeshabh/Desktop/java practice/insertWordInMiddle.java:14:
error: not a statement
String final = s_split[0]+" Tutorial"+s_split[1];

The simple answer is that final can't be the name of a variable. I can go into more detail if needed, but that's pretty much it. Try something else for your variable name.

final is a reserved keyword in Java. You can't name a variable final. Try renaming it to e.g. finalString.
Wikipedia has a list of all the reserved keywords.

final is a keyword. You can't use it as a variable name.
As per the building of strings: you could use StringBuilder, but for generating one string it's not really necessary. However, concatenating strings using the + operator will create copies of all strings involved and make baby cry when used within a loop.
When to use StringBuilder in Java

You was just a bit unlucky - you used word that is reserved for other purposes in Java language. Take a look at this list, final is present here, so you can't name variables with words listed there:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html

Related

Why JVM is giving error "incompatible type: String cannot be converted to char" and how to fix it without using other method? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
Code:
public class Test2 {
public static void main(String arga[]) {
char arr[] = {"T","h","i","s"," ","i","s"," ","a"," ","t","e","s","t"};
String str = new String(arr);
System.out.println(str);
}
}
Output:
Test2.java:5: error: incompatible types: String cannot be converted to char
char arr[] = {"T","h","i","s"," ","i","s"," ","a"," ","t","e","s","t"};
^
Where's the error in the above code and how to fix it? please dont recommend me to use other method like: String str = "This is a test"; etc etc. I want to know where's the error and how to fix this code, because I found this code on a book so I want to confirm if this is a printing mistake or something.
You are trying to create a char array with Strings. Here is the right syntax:
char arr[] = new char[]{'T','h','i','s',' ','i','s',' ','a',' ','t','e','s','t'};
String str = new String(arr);
System.out.println(str);
You are using string double quotes ". You want to use a single quote ' when working with chars.

incompatible types: String cannot be converted to int even there're no strings [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am trying to learn Java programming but when i tried to make a simple BMI calculator i get this error, The error is generated on line 7, There are no "Stings" to convert it to int actually all are "int" here! Please help!
package com.sparkedleads.bminew;
public class MyBmiNew {
public static void main(String[] args) {
int myBmi = myBmiCal("20", "10");
System.out.println("Your BMI is " + myBmi);
}
public static int myBmiCal(int massOfPerson, int heightOfPerson){
int bmiScore = massOfPerson/heightOfPerson;
return bmiScore;
}
}
You are passing two arguments as String type, "20", "10":
int myBmi = myBmiCal("20", "10");
But it should be int type:
int myBmi = myBmiCal(20, 10);
"" - it means just empty String in Java. "20" - it means String with value 20. "20" and 20 are different types in Java. Here is documentation to learn more about it.
your error is int myBmi = myBmiCal("20", "10");
putting a number in quotes makes it a string so it should be: int myBmi = myBmiCal(20, 10);
The actual problem with your code is that you have passed the arguments to
myBmiCal("20","10");
This makes the compiler think that 20 and 10 are actually String arguments instead of taking them as integer type.
make it to myBmiCal(20,10);
Let us also remember that our computers running java are nothing but dumb machines which only follow our instructions.
just remove the " from your parameter because function need int param and you sent String params
int myBmi = myBmiCal(20, 10);

How to separating parts of a java string? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I've got this string:
"type":"image","originX":"center","originY":"center","left":135,"top":259,"width":270,"height":519,"fill":"rgb(0,0,0)","overlayFill":null,"stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"src":"file:///C:/Users/Alvin%20Combrink/Dropbox/Entrepren%C3%B6rskap/Design/Hemsidan/Backgrunder/Labyrint.jpg","filters":[]},
each part is seperated by a comma, i want to be able to extract a few of the numbers into doubles. The ones i want are left, top, scaleX, scaleY and angle. How shall i approch this?
thanks
If you don't want to rely on using JSON parsers (you should, though, if you are using JSON a lot), you could use the split-method on the entire string and split according to , (comma), find the chunks of data that you want, split those according to : and read the data directly from the 2nd slot in the resulting array.
You may need to substring the last " to be able to parse the numbers directly, though.
But like I said, you really do want to use a JSON parser of some kind if you are using JSON more than a few times in your program.
Code example:
String abc = "ABC:123,DEF:456,GHI:789";
String[] chucks = abc.split(",");
String[] oneToThree = chunks[0].split(":");
String nums = oneToThree[1];
System.out.println(nums);
//This will print 123
I know that someone already replied, but I've been doing this, hope that help too:
public class HelloWorld{
public static void main(String []args){
String text ="\"type\":\"image\",\"originX\":\"center\",\"originY\":\"center\",\"left\":135,\"top\":259,\"width\":270,\"height\":519,\"fill\":\"rgb(0,0,0)\",\"overlayFill\":null,\"stroke\":null,\"strokeWidth\":1,\"strokeDashArray\":null,\"strokeLineCap\":\"butt\",\"strokeLineJoin\":\"miter\",\"strokeMiterLimit\":10,\"scaleX\":1,\"scaleY\":1,\"angle\":0,\"flipX\":false,\"flipY\":false,\"opacity\":1,\"shadow\":null,\"visible\":true,\"clipTo\":null,\"src\":\"file:///C:/Users/Alvin%20Combrink/Dropbox/Entrepren%C3%B6rskap/Design/Hemsidan/Backgrunder/Labyrint.jpg\"";
//Just left and scaleX for example
String left = readValue(text, "left");
String scaleX = readValue(text, "scaleX");
System.out.println("left:" + left);
System.out.println("scaleX:" + scaleX);
}
public static String readValue(String text, String key)
{
//search for the init of the value
int start = text.indexOf("\"" + key + "\"");
//search for the end of the value
int end = text.indexOf(",", start + key.length() + 3);
//return the value. these + 3 , is for quotes and ":"
return text.substring(start + key.length() + 3,end);
}
}

Split email address containing multiple delimiters? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How to extract email address from String like below with delimiter as "AND" ?
String str="abb#AND.comANDbbb.comANDccc#xxd.AND";
Try with following code segment,
public class TokenizerTest
{
private final String testStr = "abb#AND.comANDbbb.comANDccc#xxd.AND";
public static void main(String[] args)
{
TokenizerTest tst = new TokenizerTest();
tst.tokenize();
}
public void tokenize()
{
if(testStr != null)
{
Pattern p = Pattern.compile("[*]*AND*[^.AND]");
String[] tokens = testStr.split(p.pattern());
for(String token:tokens)
{
System.out.println(token);
}
}
}
}
It results in
abb#AND.com
bb.com
cc#xxd.AND
Short answer: Computer says no.
Based on the string you provided, it can probably not be done in a reliable way, since it is not clear what is an email address, and what is a delimiter. In fact, it is difficult to extract more than one or two valid email-addresses at all from that line.
I recommend you first check your dataset to see if it is corrupted, then find a way to use a different delimiter.

How to set a java string variable equal to "htp://website htp://website " [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
so I have a large list of websites and I want to put them all in a String variable. I know I can not individually go to all of the links and escape the //, but is there is over a few hundred links. Is there a way to do a "block escape", so everything in between the "block" is escaped? This is an example of what I want to save in the variable.
String links="http://website http://website http://website http://website http://website http://website"
Also can anyone think of any other problems I might run into while doing this?
I made it htp instead of http because I am not allowed to post "hyperlinks" according to stack overflow as I am not at that level :p
Thanks so much
Edit: I am making a program because I have about 50 pages of a word document that is filled with both emails and other text. I want to filter out just the emails. I wrote the program to do this which was very simple, not I just need to figure away to store the pages in a string variable in which the program will be run on.
Your question is not well-written. Improve it, please. In its current format it will be closed as "too vague".
Do you want to filter e-mails or websites? Your example is about websites, you text about e-mails. As I don't know and I decided to try to help you anyway, I decided to do both.
Here goes the code:
private static final Pattern EMAIL_REGEX =
Pattern.compile("[A-Za-z0-9](:?(:?[_\\.\\-]?[a-zA-Z0-9]+)*)#(:?[A-Za-z0-9]+)(:?(:?[\\.\\-]?[a-zA-Z0-9]+)*)\\.(:?[A-Za-z]{2,})");
private static final Pattern WEBSITE_REGEX =
Pattern.compile("http(:?s?)://[_#\\.\\-/\\?&=a-zA-Z0-9]*");
public static String readFileAsString(String fileName) throws IOException {
File f = new File(fileName);
byte[] b = new byte[(int) f.length()];
InputStream is = null;
try {
is = new FileInputStream(f);
is.read(b);
return new String(b, "UTF-8");
} finally {
if (is != null) is.close();
}
}
public static List<String> filterEmails(String everything) {
List<String> list = new ArrayList<String>(8192);
Matcher m = EMAIL_REGEX.matcher(everything);
while (m.find()) {
list.add(m.group());
}
return list;
}
public static List<String> filterWebsites(String everything) {
List<String> list = new ArrayList<String>(8192);
Matcher m = WEBSITE_REGEX.matcher(everything);
while (m.find()) {
list.add(m.group());
}
return list;
}
To ensure that it works, first lets test the filterEmails and filterWebsites method:
public static void main(String[] args) {
System.out.println(filterEmails("Orange, pizza whatever else joe#somewhere.com a lot of text here. Blahblah blah with Luke Skywalker (luke#starwars.com) hfkjdsh fhdsjf jdhf Paulo <aaa.aaa#bgf-ret.com.br>"));
System.out.println(filterWebsites("Orange, pizza whatever else joe#somewhere.com a lot of text here. Blahblah blah with Luke Skywalker (http://luke.starwars.com/force) hfkjdsh fhdsjf jdhf Paulo <https://darth.vader/blackside?sith=true&midclorians> And the http://www.somewhere.com as x."));
}
It outputs:
[joe#somewhere.com, luke#starwars.com, aaa.aaa#bgf-ret.com.br]
[http://luke.starwars.com/force, https://darth.vader/blackside?sith=true&midclorians, http://www.somewhere.com]
To test the readFileAsString method:
public static void main(String[] args) {
System.out.println(readFileAsString("C:\\The_Path_To_Your_File\\SomeFile.txt"));
}
If that file exists, its content will be printed.
If you don't like the fact that it returns List<String> instead of a String with items divided by spaces, this is simple to solve:
public static String collapse(List<String> list) {
StringBuilder sb = new StringBuilder(50 * list.size());
for (String s : list) {
sb.append(" ").append(s);
}
sb.delete(0, 1);
return sb.toString();
}
Sticking all together:
String fileName = ...;
String webSites = collapse(filterWebsites(readFileAsString(fileName)));
String emails = collapse(filterEmails(readFileAsString(fileName)));
I suggest that you save your Word document as plain text. Then you can use classes from the java.io package (such as Scanner to read the text).
To solve the issue of overwriting the String variable each time you read a line, you can use an array or ArrayList. This is much more ideal than holding all the web addresses in a single String because you can easily access each address individually whenever you like.
For your first problem, take all the text out of word, put it in something that does regular expressions, use regular expressions to quote each line and end each line with +. Now edit the last line and change + to ;. Above the first line write String links =. Copy this new file into your java source.
Here's an example using regexr.
To answer your second question (thinking of problems) there is an upper limit for a Java string literal if I recall correctly 2^16 in length.
Oh and Perl was basically written for you to do this kind of thing (take 50 pages of text and separate out what is a url and what is an email)... not to mention grep.
I'm not sure what kind of 'list of websites' you're referring to, but for eg. a comma-separated file of websites you could read the entire file and use the String split function to get an array, or you could use a BufferedReader to read the file line by line and add to an ArrayList.
From there you can simply loop the array and append to a String, or if you need to:
do a "block escape", so everything in between the "block" is escaped
You can use a Regular Expression to extract parts of each String according to a pattern:
String oldString = "<someTag>I only want this part</someTag>";
String regExp = "(?i)(<someTag.*?>)(.+?)(</someTag>)";
String newString = oldString.replaceAll(regExp, "$2");
The above expression would remove the xml tags due to the "$2" which means you're interested in the second group of the expression, where groups are identified by round brackets ( ).
Using "$1$3" instead should then give you only the surrounding xml tags.
Another much simpler approach to removing certain "blocks" from a String is the String replace function, where to remove the block you could simply pass in an empty string as the new value.
I hope any of this helps, otherwise you could try to provide a full example with you input "list of websites" and the output you want.

Categories