How do I add commas when converting from Int [] to String? [duplicate] - java

This question already has answers here:
How to remove last comma and space in array? Java [duplicate]
(3 answers)
Closed 5 months ago.
Hei
I'm a beginner in Java and I have homework and I spent all day trying to figure out the solution and I couldn't. I'm so frustrated
Can someone help me?
Converting from any table in Int [] to string for eksmpel : int [] a = { 1,2,3} to String s = [1,2,3]
I didn't know how to put the comma, it always shows a trailing comma at the end or at the beginning a trailing comma as well as parentheses.
This is my code :
public class Test11 {
public static String til(int[] tabell) {
String str = "";
String na1 = "[";
String na2 = "]";
String na3 = ",";
String str3 = "";
for (int i = 0; i < tabell.length; i++) {
str += "," + tabell[i];
}
return str;
}
public static void main(String[] args) {
int[] tab = { 1, 2, 3 };
System.out.println(til(tab));
}
}

You need to handle the first iteration through your loop as a special case, because you don't want to add a comma the first time around. There's something you can use to know that you're in the first iteration...the fact that the string you're building is empty because you haven't added anything to it yet.
This makes extra good sense because if the string is empty, then it doesn't yet contain a term that you want to separate from the next term with a comma.
Here's how you do this:
String str = "";
for (int i = 0; i < tabell.length; i++) {
if (str.length() > 0)
str += ",";
str += tabell[i];
}

Use a variable to keep track of whether or not you're on the first iteration. If you are, don't put a comma before it.
boolean isFirst = true;
for (int i = 0; i < tabell.length; i++) {
if (!isFirst) {
str += ",";
}
isFirst = false;
str += tabell[i];
}

Related

How can i iterate a String and grab several data from there? [duplicate]

This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 4 years ago.
I have this method:
public void separator(){
int count=0, i=0;
while (count == 0) {
if (track1result.charAt(i) != '^') {
char c = track1result.charAt(i);
number += c;
} else {
count++;
}
i++;
}
}
It's supposed to iterate a String until he reaches the ^ symbol, and that's great, and working so far, the problem is that i'm not sure how can i like keep going from there so i can get the string that's after the symbol and store it in another variable.
If you can give me ideas i would really appreciate it!
you can just split the String into array
String s1 = "hello^world";
String[] arr = s1.split("\\^");
String firstpart = arr[0];
String secondpart = arr[1];
System.out.println(firstpart+" "+secondpart);
Inside the else part add this:
if (i < track1result.length() - 1)
rest = track1result.substring(i + 1);
where rest is previously declared:
String rest = "";

Is converting to String the most succinct way to remove the last comma in output in java?

So basically this is how my code looked like
public static void printPrime(int[] arr)
{
int len = arr.length;
for(int i = 0; i < len; i++)
{
int c = countFactor(arr[i]);
if(c == 2)
{
System.out.print(arr[i] + ",");
}
}
}
So the output did have the 'comma' in the end. I tried looking around to remove the last comma some answers say to print last element separately but that can only happen when output depends on the for loop and not the if condition.
But as you can see I don't know how many elements I am going to get from the if condition. Only two things I can think of, to add another loop or use String then substr to output.
So I converted it to String
public static void printPrime(int[] arr)
{
int len = arr.length;
String str = "";
for(int i = 0; i < len; i++)
{
int c = countFactor(arr[i]);
if(c == 2)
{
str = str + arr[i] + ",";
}
}
str = str.substring(0, str.length()-1);
System.out.println(str);
}
My question is about knowing the optimum way (converting to string then substringing it?) for similar questions or could there be a better way as well? That I seem to be missing.
You don't have to construct a string. Consider the following slight tweaks:
public static void printPrime(int[] arr)
{
int len = arr.length;
String sep = ""; // HERE
for(int i = 0; i < len; i++)
{
int c = countFactor(arr[i]);
if(c == 2)
{
System.out.print(sep); // HERE
sep = ",";
System.out.print(arr[i]);
}
}
}
Print the delimiter first, and store its value in a variable: the first time it's printed, it will print the empty string. Thereafter, it prints the comma.
Whatever means you use should operate correctly for an empty array (length 0), a singleton array (length 1) and a long array (a large length).
Adding the comma then removing it requires special case handling for the empty array case. So you must have conditional code (an if statement) whatever you do.

Ouput of Reversing words of String does not come as expected [duplicate]

This question already has answers here:
Reverse a given sentence in Java
(14 answers)
Closed 7 years ago.
Given a String with words.Reverse words of String.
Sample Input 1
Hello World
Sample Output
World Hello
MyApproach
To reverse words I first counted how many spaces are there.After that I stored their space index in an array.Using lastIndex, I printed the last elements of the array.After that I printed the last 2 words of the array.
static String reverseWords(String inputString)
{
int l1=inputString.length();
int count=1;
for(int i=0;i<l1;i++)
{
char ch=inputString.charAt(i);
if(ch==' ')
{
count++;
}
}
int k=0;
int[] spaceindex=new int[count];
spaceindex[0]=0;
k++;
for(int i=0;i<l1;i++)
{
char ch=inputString.charAt(i);
if(ch==' ')
{
spaceindex[k++]=i+1;
}
}
int p=spaceindex.length-1;
String strnew="";
for(int j=spaceindex[p];j<l1;j++)
{
char c=inputString.charAt(j);
strnew=strnew+c;
}
p--;
while(p>=0)
{
for(int j=spaceindex[p];;j++)
{
char c=inputString.charAt(j);
if(c==' ')
{
break;
}
strnew=strnew+c;
}
}
return strnew;
}
InputParameters ActualOutput Expected Output
Hello World WorldHelloWorldHello(Infinite loop) WorldHello
#Edit I asked Why the code I wrote is wrong.I tried without using any inbuilt functions(which was necessary for me).In that way I think It is not Duplicate Ans according to me.
Can anyone guide me what went wrong in my code.
The issue within your code was the while loop:
while(p>=0) {
strnew = strnew + " ";
for(int j=spaceindex[p];;j++) {
char c=inputString.charAt(j);
if(c==' '){
break;
}
strnew=strnew+c;
}
p--;
}
Adding the p-- will prevent the loop for occurring infinitely. Also inserting the strnew = strnew + " "; after the while loop ensures a space in between each word.
It's possible without using another arrays, splits or any additional strucure.
Having array of characters ( convert if needed as String is immutable), first reverse all characters in the array. Secondly loop over spaces and for each word reverse characters in the word.
Simple solution :
public static void main(String[] args) {
String x = "Hello World";
String[] xArray = x.split(" ");
String result = "";
for (int i = xArray.length - 1; i >= 0; i--) {
result += xArray[i] + " ";
}
System.out.println(result.trim()); // World Hello
}
You can use a StringTokenizer to convert the string into tokens or String.split function. You can push this collection into a Stack and extract the elements in a reverse order. To join the strings back you could use a StringBuilder or a StringBuffer.
To do this more efficiently you could convert the string to a character array and StringBuilders
String myString = "Here is the String";
char[] myChars = myString.toCharArray();
StringBuilder word = new StringBuilder();
StringBuilder newString = new StringBuilder();
for(int i = myChars.length - 1; --i >= 0;) {
char c = myChars[i];
if(c == ' ') {
newString.append(c);
newString.append(word);
word = new StringBuilder();
} else {
word.append(c);
}
}
I would base an implementation on String.lastIndexOf(int) and String.substring(int, int). I'd got with a StringBuilder to construct the output "sentence" and a while loop to iterate the words in reverse order. Something like,
static String reverseWords(String in) {
StringBuilder sb = new StringBuilder(in.length());
int space;
while ((space = in.lastIndexOf(' ')) > 0) {
sb.append(in.substring(space + 1, in.length())).append(' ');
in = in.substring(0, space);
}
sb.append(in);
return sb.toString();
}
Which I tested with your provided sample
public static void main(String[] args) {
System.out.println(reverseWords("Hello World"));
}
Getting (as expected)
World Hello

Return word specified by the integer

I know I'm missing some things and that's what I really need help with. The code doesn't work in all cases and am looking for help improving/fixing it.
Assignment:
The code I have so far:
public String word(int num, String words)
{
int l = words.indexOf(" ");
int r = words.indexOf(" ", l+1);
for(int i = 3; i <= num; i++){
l = r;
r = words.indexOf(" ", l+1);
//if(i != num)
// l = r;
}
String theword = words.substring(l,r);
return theword;
}
}
As this is clearly homework, I will give you text only.
Your approach may work eventually, but it is laborious and overly complicated, so it's hard to debug and hard to get right.
make use of String's API by using the split() method
after splitting the sentence into an array of word Strings, return the element at num less one (array are indexed starting at zero
check the length of the array first, in case there are less words than num, and take whatever action you think is appropriate in that case
For part 2, a solution in a simple form may be:
create a new blank string for the result
iterate over the characters of the given string adding the character to the front of the result string
make use of String's toUpperCase() method
Since this is homework and you have showed some effort. This is how you can do part 1 of your question. This code is pretty evident.
1) I am returning null if number is greater than the number of words in string as we dont want user to enter 5 when there are only 2 words in a string
2) Splitting the string by space and basically returning the array with the number mentioned by user
There are more conditions which you must figure out such as telling the user to enter a number of the string length since it would not give him any result and taking input from Scanner instead of directy adding input in method.
public static String word(int num, String words)
{
String wordsArr[] = words.split(" ");
if(num <= 0 || num > wordsArr.length) return null;
return (wordsArr[num-1]);
}
the second part of your question must be attempted by you.
Well... not often you see people coming here with homework AND showing effort at the same time so bravo :).
This is example of how you can split the string and return the [x] element from that string
public class SO {
public static void main(String[] args) throws Exception {
int number = 3;
String word = "Hello this is sample code";
SO words = new SO();
words.returnWord(number, word);
}
private void returnWord(int number, String word) throws Exception {
String[] words = word.split("\\s+");
int numberOfWords = words.length;
if(numberOfWords >= number) {
System.out.println(words[number-1]);
} else {
throw new Exception("Not enought words!!!");
}
}
}
Yes it is a working example but do not just copy and paste that for your homework - as simple question from teacher - What is this doing, or how this works and your out :)! So understand the code, and try to modify it in a way that you are familiar what is doing what. Also its worth getting some Java book - and i recommend Head first Java by O'Really <- v.good beginner book!
if you have any questions please do ask!. Note that this answer is not 100% with what the textbook is asking for, so you can modify this code accordingly.
As of part 2. Well what Bohemian said will also do, but there is a lot quicker solution to this.
Look at StringBuilder(); there is a method on it that will be of your interest.
To convert String so all letter are upper case you can use .toUpperCase() method on this reversed string :)
You can try:
public class trial {
public static void main(String[] args)
{
System.out.println(specificword(0, "yours faithfully kyobe"));
System.out.println(reverseString("derrick"));}
public static String specificword(int number, String word){
//split by space
String [] parts = word.split("\\ ");
if(number <= parts.length){
return parts[number];
}
else{
return "null String";
}
}
public static String reverseString(String n){
String c ="";
for(int i = n.length()-1; i>=0; i--){
char m = n.charAt(i);
c = c + m;
}
String m = c.toUpperCase();
return m;
}
}
For the first problem, I'll give you two approaches (1. is recommended):
Use the String.split method to split the words up into an array of words, where each element is a word. Instead of one string containing all of the words, such as "hello my name is Michael", it will create an array of the words, like so [hello, my, name, is, Michael] and that way you can use the array to access the words. Very easy:
public static String word(int num, String words)
{
// split words string into array by the spaces
String[] wordArray = words.split(" "); // or = words.split("\\s+");
// if the number is within the range
if (num > 0 && num <= wordArray.length) {
return wordArray[num - 1]; // return the word from the word array
} else { // the number is not within the range of words
return null;
}
}
Only use this if you cannot use arrays! Loop through the word until you have found enough spaces to match the word you want to find:
public static String word(int num, String words)
{
for (int i = 0; i < words.length(); i++) { // every character in words
if (words.substring(i, i+1).equals(" ")) { // if word is a space
num = num - 1; // you've found the next word, so subtract 1 (number of words left is remaining)
}
if (num == 1) { // found all words
// return this word
int lastIndex = i+1;
while (lastIndex < words.length()) { // until end of words string
if (words.substring(lastIndex, lastIndex+1).equals(" ")) {
break;
}
lastIndex = lastIndex + 1; // not a space so keep moving along the word
}
/*
// or you could use this to find the last index:
int lastIndex = words.indexOf(" ", i + 1); // next space after i+1
if (lastIndex == -1) { // couldn't find another space
lastIndex = words.length(); // so just make it the last letter in words
}*/
if (words.substring(i, i+1).equals(" ")) { // not the first word
return words.substring(i+1, lastIndex);
} else {
return words.substring(i, lastIndex);
}
}
}
return null; // didn't find word
}
As for the second problem, just iterate backwards through the string and add each letter to a new string. You add each letter from the original string to a new string, but just back to front. And you can use String.toUpperCase() to convert the string to upper case. Something like this:
public static String reverse(String str) {
String reversedString = ""; // this will be the reversed string
// for every character started at the END of the string
for (int i = str.length() - 1; i > -1; i--) {
// add it to the reverse string
reversedString += str.substring(i, i+1);
}
return reversedString.toUpperCase(); // return it in upper case
}

Unable to convert to Int from String

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);
}

Categories

Resources