so first here is my code :
public class eol {
public static void main(String[] args) {
String x = "Charles.Baudelaire*05051988*France Sergei.Esenin*01011968*Russia Herman.Hesse*23051996*Germany";
String[] word= x.split("[.,*, ]");
for(int i=0;i<word.length;i++){
// System.out.print(word[i]+" ");
}
String name = word[0];
String lastname = word[1];
String dod =word[2];
String cob= word[3];
System.out.print("First person data : "+
"\n"+ name +" "+ "\n"+lastname+" "+"\n"+ dod+" "+"\n"+ cob);
I want to loop through string x, and take needed values, and use them to make 3 objects of class writer, is there any way i do this with for loop ?
Or would i have to "break" original string in 3 smaller arrays, then do for loop for every one of them.
I mean, i can use for loop to print out data on screen, by incrementing counter by certain value, how ever to add these data to fields is something I don't understand how to do.
Sure. You can do the following:
Validate.isTrue(word.length % 4 == 0, "Array size must be a multiple of 4");
List<Writer> writers = new ArrayList<>();
for (int i=0; i<word.length; i+=4) {
String name = word[i];
String lastname = word[i+1];
String dod =word[i+2];
String cob= word[i+3];
writers.add(new Writer(name, lastname, dod, cob));
}
i += 4 instead of i++ after each tern of loop, and use word[i], word[i+1], word[i+2] and word[i+3] in loop.
i.e.
String x = "Charles.Baudelaire*05051988*France Sergei.Esenin*01011968*Russia Herman.Hesse*23051996*Germany";
String[] word= x.split("[.,*, ]");
for(int i=0;i<word.length;i+=4){
String name = word[i];
String lastname = word[i+1];
String dod =word[i+2];
String cob= word[i+3];
// Use these variable.
}
Related
Hi guys! =)
I'm new to Java, currently, I'm learning arrays and loops. I have an interesting homework task that I am very confused about.
And I don't know what to do with this one. So I need your advice.
Create a public String getCheapStocks(String[] stocks) method in it. It takes an array of strings as input. Each line consists of the name of the product and its price, separated by a single space.
The method returns a string - a list of product names whose price is less than 200.
And the getCheapStocks(new String[] {"gun 500", "firebow 70", "pixboom 200"}) returns "firebow".
There is only for loop can be used.
I found a method that can split a string:
String text = "123 456"
String[] parts = text.split(" ")
int number1 = Integer.parseInt(parts[0]) //123
int number2 = Integer.parseInt(parts[1]) //456
But when I have String "gun 500" I can only split it in two String. And I can't compare it to 200. My code is a mess and it does nothing.
I would really appreciate any tips or advice, thanks in advance!
public static String getCheapStocks(String[] stocks) {
//MESS!
int max = 200;
for(int i = 0; i < stocks.length; i++) {
String txt = stocks[i];
String[] parts = txt.split(" ");
int number1 = Integer.parseInt(parts[0]);
int number2 = Integer.parseInt(parts[1]);
if(number1 < max) {
}
}
}
public static void main(String[] args) {
//returns "firebow"
System.out.println(getCheapStocks(new String[] {"gun 500", "firebow 70", "pixboom 200"}));
}
}
Since your input is in format of "<stock> <price>", after splitting this into 2 parts, you have to convert only the second part to an integer, otherwise you will get an exception.
public static String getCheapStocks(String[] stocks) {
// Use a StringBuilder to hold the final result
StringBuilder result = new StringBuilder();
for (String stock : stocks) {
String[] parts = stock.split(" ");
// If the price is lower than 200, append part[0] (stock name) to the result
if (Integer.parseInt(parts[1]) < 200) {
result.append(parts[0]).append(" "); // Append also a space character for dividing the stocks
}
}
// Strip the space from the end
return result.toString().trim();
}
public static String getCheapStocks(String[] stocks) {
int maxPrice = 200;
List<String> results = new ArrayList<>();
for (String txt : stocks) {
String[] parts = txt.split(" ");
String stockName = parts[0];
int price = Integer.parseInt(parts[1]);
if (price < maxPrice) {
results.add(stockName);
}
}
return String.join(" ", results);
}
If there is some text given, I need to search the word with maximum length.So I thought this way.
public class Foo {
public static void main(String[] args) {
String str = "java string split method by javatpoint";
String words[] = str.split("\\s");//splits based on white space
for(String w:words) {
//System.out.println(w);
String temp = w;
if(temp.length()<w.length()) {
String maxLengthString = w;
System.out.println("maxLengthString is w");
}else {
System.out.println("maxLengthString is temp");
}
}
}
}
Store the longest in temp, and only (try) to print it after the loop. Re-assign temp each time you encounter a longer word.
for(String w:words) {
//System.out.println(w);
String temp = w;
if(temp.length()<w.length()) {
String maxLengthString = w;
System.out.println("maxLengthString is w");
}else {
System.out.println("maxLengthString is temp");
}
}
This will print each iteration, which is not what you want. In order to keep the longest word, you'll need to declare temp outside of the loop.
String temp = "";
for(String w:words) {
// this will override temp only if the word is longer
if ( w.length() > temp.length() ) {
temp = w;
}
}
// don't print harcoded "temp", but concatenate the value of the variable temp
System.out.println("The longest word is: " + temp);
Hey, kindly read the comments in the code, it will help understand what's going on.
public static void main(String[] args) {
String str = "java string split method by javatpoint";
String words[] = str.split("\\s");//splits based on white space
int max =0;
String maxWord = "";
for(String w:words) {
max = maxWord.length(); /* assigning the length of maxWord on every iteration since it might change */
int mightBeNewMax = w.length(); /* always instantiating a newlenght that might be greater than previous, also this saves us the recreation below incase we wan to assign it as the new max length*/
if(max<mightBeNewMax) {/* here we simply check the previous max against the new one */
/* getting to this block means we have a new max length so we simply update our initially declared variables above. */
maxWord = w;
max = mightBeNewMax;
}
}
//Below is just a concatenated strings to make sense out of our code.
System.out.println("maxLengthString is: "+ maxWord + " With length of: "+max);
}
Note: I removed your else statement because we don't want to do anything when the new string we're looping on is less than the previous one, so we only care about new longer lengths of strings.
Initialise a string with length 0 and compare it with the each string in the array and update the maxString found in each iteration in the end you will have the maxString.
public class Foo {
public static void main(String[] args) {
String str = "java string split method by javatpoint";
String words[] = str.split("\\s");//splits based on white space
String maxString = "";
for(String w:words) {
if(w.length() > maxString.length()) {
maxString = w;
}
}
System.out.println(maxString);
}
Alternatively you can use streams for the same :
String str = "string split method by javatpoint javatpoint";
String words[] = str.split("\\s");//splits based on white space
List<String> names = Arrays.asList(words);
Optional<String> result =
names.stream().max(Comparator.comparingInt(String::length));
System.out.println(result.get());
Is it possible to check if a substring contains a certain value and do something? I have this piece of code i'm wondering if I could check if desc: contains the value \n I have the config made with the following information
test: desc:\ndog\ntest
test2: desc:\ndog3
So how would I be able to retrieve the \n and loop through all the \n in that specific string list and do a action.
for (String s : plugin.file.getFile().getStringList(plugin.file.path))
{
public void substring(){
String labels = "item: desc:";
String[] parts = labels.split(" ");
String part1 = parts[0];
String part2 = parts[1];
System.out.println("Desc Value: " + s.substring(part2.length()).split(" ")[1])
}
}
I don't understand your question in full but I think that you want something like this:
String test = "desc:\ndog\ntest";
String test1 = "desc:\ndog3";
String[] parts = test.split(":");
String name = parts[0];
String[] values = parts[1].trim().split("\n");
System.out.println("Name: " + name);
for (int i = 0; i<values.length; i++)
{
System.out.println(values[i]);
}
You just split the values of [1] index in that parts table.
I cannot figure out how to change the order of a given name.
For example: Van-Dame Claud
Result: Claud Dame-Van
I created this method, but it seems that is not correct, any suggestion or maybe a better method?
public String NameInvers(){
String Name, Name = null, Name = null, NameFinal;
int s1 = getName().indexOf(' ');
int s2 = getName().indexOf('-');
if(s1 != 0){
Name1 = getName().substring(0, s1);
if(s2 != 0)
{
Name2 = getName().substring(s1, s2);
Name3 = getName().substring(s2);
}
NameFinal = Name3 + Name2 + Name1;
}
else
NameFinal = getName();
return NameFinal;
}
Edit: In my Main method I have a number of names. The thing is that it says: throw new StringIndexOutOfBoundsException(subLen) and it won't show up.
Here you go:
public static String reverseName (String name) {
name = name.trim();
StringBuilder reversedNameBuilder = new StringBuilder();
StringBuilder subNameBuilder = new StringBuilder();
for (int i = 0; i < name.length(); i++) {
char currentChar = name.charAt(i);
if (currentChar != ' ' && currentChar != '-') {
subNameBuilder.append(currentChar);
} else {
reversedNameBuilder.insert(0, currentChar + subNameBuilder.toString());
subNameBuilder.setLength(0);
}
}
return reversedNameBuilder.insert(0, subNameBuilder.toString()).toString();
}
Test:
public static void main(String[] args) {
printTest("Van-Dame Claud");
printTest("Victor Hugo");
printTest("Anna");
printTest("");
}
private static void printTest(String S) {
System.out.printf("Reverse name for %s: %s\n", S, reverseName(S));
}
Output:
Reverse name for Van-Dame Claud: Claud Dame-Van
Reverse name for Victor Hugo: Hugo Victor
Reverse name for Anna: Anna
Reverse name for :
First of all, you duplicate your variable Name declaration, three times. I suppose that you want to put:
String Name1, Name2 = null, Name3 = null, NameFinal;
instead of:
String Name, Name = null, Name = null, NameFinal;
Then, if you just have 2 names with a - in the middle and you want to change their order you can use split function to separate it, finding where - is. You can use it like this:
String string = "Van-Dame Claud";
String[] divide = string.split("-");
String Name1 = divide[0];
String Name2 = divide[1];
String result = Name2 + "-" + Name1;
EDIT: Name1 will be Van and Name2 will be Dame Claud so the result will be Dame Cloud-Van.
I expect it works for you!
You want to have a method to convert all names or just the the names in form of Name-Name Name? I'm assuming you want a method for all names. Since if you just want to reverse names in this specific form, there is no meaning for you to check value of s1 and s2, you know s1 and s2 must be a positive number. If you check because you want to do error checking, then you should throw an exception if the name is not in the form you want. If you want to do it for all names, below is the pseudocode, you can implement it yourself (your code contains several errors, you are using Name1, Name2, Name3, but you never declared them and duplicate variable Name declaration):
string finalName = ""
string [] strs1 = name split by " "
foreach str1 in strs1
string [] strs2 = str1 split by "-"
foreach str2 in strs2
if str2.first?
finalName = str2 + " " + finalName
else
finalName = str2 + "-" + finalName
end
end
end
return finalName.substring 0, finalName.length-1 //remove the space at the end
I think this would work. Hope you find it useful.
I am working on a solution to the TSP problem. I have generated all the permutations of the String "123456", however, I need to convert this into an ArrayList of Integer like this [1,2,3,4,5,6]...[6,5,4,3,2,1]. I then store this into an ArrayList of ArrayLists. Once there I will be able to compare all of the cities that need to be traveled to.
When I run my code, I have a method to generate the permutation, then a method to change that permutation into an ArrayList of Integer. When I convert them, I get the exception java.lang.NumberFormatException: For input string: "". I don't know of any other way to get the String to Integer
Here is my code.
public static String permute(String begin, String string){
if(string.length() == 0){
stringToIntArray(begin+string);
return begin + string + " ";
}
else{
String result = "";
for(int i = 0; i < string.length(); ++i){
String newString = string.substring(0, i) + string.substring(i+1, string.length());;
result += permute(begin + string.charAt(i), newString);
}
stringToIntArray(result);
return result;
}
}
public static void stringToIntArray(String s){
ArrayList<Integer> perm = new ArrayList<Integer>();
String [] change = s.split("");
for(int i = 0; i < 7; ++i){
int integer = Integer.parseInt(change[i]);
System.out.println(integer);
}
}
public static void main(String[] args) {
permute("", "123456");
}
These lines
String [] change = s.split("");
for(int i = 0; i < 7; ++i){
int integer = Integer.parseInt(change[i]);
System.out.println(integer);
}
Given a String like "12345", when you split it on nothing, it will separate every character. Giving you an array with ["","1","2","3","4","5"]. Since the empty String "" is not a Number, you will get the NumberFormatException. You could change your index i to start at 1 so as to ignore that first empty String.
The split method, when splitting on "", produces an empty string as the first element of the array, so you need to start iterating from i = 1.
Also, it would be safer to stop the iteration at change.length to make sure you process all characters when there are more than 6, and don't go out of bounds if there are fewer.
String [] change = s.split("");
for(int i = 1; i < change.length; ++i){ // ignore first element
int integer = Integer.parseInt(change[i]);
System.out.println(integer);
}