Why am I getting variable not initialized error? - java

I am trying to get all the characters from a string to a 2D character array. The details are given below:
My code:
import java.util.*;
public class Main
{
public static void main(String[] args) {
//System.out.println("Hello World");
Scanner sc=new Scanner(System.in);
int n,l=0; //as you can see, n is initialized
String x="";
char[][] arr1=new char[10][10];
if(sc.hasNextInt())
n=sc.nextInt();
for(int i=0;i<n;i++){
if(sc.hasNextLine())
x=sc.nextLine();
//char[] arr=x.toCharArray();
if(x.length()==n){
for(int j=l;j<arr1.length;j++){
for(int k=0;k<arr1.length;k++){
arr1[j][k]=x.charAt(i);
}
x="";
++l;
break;
}
}
}
System.out.println(arr1);
}
}
Error:
error: variable n might not have been initialized
for(int i=0;i<n;i++){
What's this? Variable n is already initialized. How do I fix this?

You can only replace a char with a char or a CharSequence with a CharSequence (as those are the only overloads defined for String#replace), not a char with a String. Converting the first argument to a String (which is a CharSequence) with String.valueOf will solve the issue.
ar[j] = ar[j].replace(String.valueOf(ar[i].charAt(k)), "");

If you are allowed to use Java 8 stream API, method simplify may be presented as follows:
using Stream reduce operation to join strings in the input array
using String replaceAll method with a regexp replacing all previously detected characters with empty literal:
public static String simplify(String... arr) {
return Arrays
.stream(arr)
.reduce("", // empty accumulator
(s1, s2) -> s1 + (s1.isEmpty() ? s2 : s2.replaceAll("[" + s1 + "]", ""))
);
}
Tests:
System.out.println(simplify("abcdef", "fghij"));
System.out.println(simplify("abcdef", "fghij", " jklmn"));
Output
Online demo
abcdefghij
abcdefghij klmn

Related

Array values do not update

I am trying to use the string after I passed it through my cleanUp function. When I return the arguments it no longer keeps the same value.
My initial strings have punctuations.
I pass the strings to a method to clean up the punctuations.
I return the modified strings back to my main method.
I print out the modified string but my results have returned to the original value of the string.
public class test{
public static void main(String[] args){
String str1 = "this-is.first:sentence/.";
String str2 = "this=is.second:sentece.";
String[] arr = cleanUp(str1, str2);
for (String string : arr){
System.out.println("string after cleanup()" + string);
}
}
public static String[] cleanUp(String str1, String str2) {
String[] arr = {str1, str2};
for (String string : arr){
string = string.replaceAll("\\p{Punct}","");
System.out.println("string cleaned:" + string);
}
return new String[] {str1, str2};
}
}
Current Output:
string cleaned: this is first sentence
string cleaned: this is second sentece
string after cleanup(): this-is.first:sentence/.
string after cleanup(): this=is.second:sentece.
Expected Output:
string cleaned: this is first sentence
string cleaned: this is second sentece
string after cleanup(): this is first sentence
string after cleanup(): this is second sentece
You have two issues in your code which have to do with the fact that Java is pass-by-value.
You are re-assigning your local string variable in the loop, not what is inside the array. So string has the correct value, the string in array still has the old value.
Your output is build out of string1 and string2 which you did never update. Your updated content is supposed to be in the arr array you built using your loop. So you must either update the values based on the arrays content or return the arrays content or directly the array
Here is a fixed version:
public static String[] cleanUp(String str1, String str2) {
String[] arr = { str1, str2 };
for (int i = 0; i < arr.length; i++) {
arr[i] = arr[i].replaceAll("\\p{Punct}", "");
System.out.println("string cleaned:" + arr[i]);
}
return arr;
}
A Java String is immutable, and when you use the for-each loop it hides your iterator. Basically, your current code is almost correct but instead of using a for-each loop and locally modifying a temporary String, use a regular loop and modify the array you generate on the first line. Also, you should return that array instead of creating a new one. And, I assume you wanted to keep some white-space in your output. Something like,
public static String[] cleanUp(String str1, String str2) {
String[] arr = { str1, str2 };
for (int i = 0; i < arr.length; i++) {
arr[i] = arr[i].replaceAll("\\p{Punct}", " ").replaceAll("\\s+", " ");
System.out.println("string cleaned:" + arr[i]);
}
return arr;
}
Which I tested with your other code (and it returns)
string cleaned:this is first sentence
string cleaned:this is second sentece
string after cleanup()this is first sentence
string after cleanup()this is second sentece

Shuffle two Strings recursively to make another String

I'm trying to create a method shuffle (String stri, String str2, String str3) that returns a boolean and take two Strings and "shuffles" them to make a third String, but I'm trying to do it recursively, which is kind of tough for me to think about. I want to return true if str1 and str2can be shuffled and return false if they can't be shuffled.
For example, if str1 = "tv" and str2 = "aol", the method might return taovl.
I also plan to test the method out as well as create another helper method to make it more efficient, but that's easy.
import java.util.Scanner;
public class lab3{
public static void main(String[] args) {
String str;
System.out.print("Enter String: ");
Scanner sc = new Scanner(System.in);
str = sc.nextLine();
String res = revRec3(str);
System.out.println(res);
}
public static String revRec3(String str)
{
if (str.length() <= 1)
return str;
else{
String first = str.substring(0, str.length() / 3);
String second = str.substring(str.length() / 3, ((2 * str.length()) / 3));
String third = str.substring((2 * str.length()) / 3, str.length());
return revRec3(third)+revRec3(second)+revRec3(first);
}
}
}
try doing something like this. This Program splits a String into 3 pieces and then reverses them using recursion.
I solved this by simply creating three integer variables to go through the indices of all three strings and checking to see if a a letter at any index matches the same order of s3

Concatenation of integers in string

I have a string as follows
String str = "AUTHOR01BOOK"
In this string I want to add this number 00001. How can I do that?
I tried concatenate it but the output I got is AUTHOR01BOOK1. My code is not appending zeros. How can I do that?
You can use the print format.
String str="AUTHOR01BOOK";
int num = 000001;
System.out.printf("%s%06d", str, num);
or use the String.format function to store it in a variable:
String myConcat = String.format("%s%05d", str, num);
EDIT:
To answer raju's follow up question about doing this in a loop,
Create a method that will return the formatted string:
static String myConcatWithLoop(String str, int iteration){
return String.format("%s%05d", str, iteration);
}
then call this in your loop:
for (int i = 1; i <= 100; i++) {
System.out.println(myConcatWithLoop(str, i));
}
if you store '000001' in int datatype it will treat as an octal. That is
int a=000001;
System.out.println(a);
Output: 1
It will treat it as OCTAL number
So you cannot store a number beginning with 0 in int as compiler will typecast it. Therefore for that you have to work with Strings only :)
Another approach is use StringBuilder
public class JavaApplication {
public static void main(String[] args) {
JavaApplication ex = new JavaApplication();
String str = "AUTHOR01BOOK";
System.out.println(ex.paddingZero(str));
}
public String paddingZero(String str) {
StringBuilder sb = new StringBuilder();
sb.append(str);
sb.append("00001");
return sb.toString();
}
}
Please try the below code. It not only displays but also changes the string.
StringUtils help us to pad the left zeros.
Number 4 in the leftPad method denotes the number of zeros.
Its not a dynamic solution but it fulfills your need.
import org.apache.commons.lang.StringUtils;
public class Interge {
public static void main(String[] args) {
int i =00001;
String s= i+"";
String result = StringUtils.leftPad(s, 4, "0");
String fnlReslt = "AUTHOR01BOOK"+result;
System.out.println("The String : " + fnlReslt);
}
}

Java String With Spaces

and thank you for helping me.
So my question is i need a code that asks you for a String like "1234 567" (input), then returns the string numbers like "1 2 3 4 5 6 7" (output) once more
my current code is:
public class StringComEspaços {
public static String formatNumberWithSpaces(String inputString) {
String outputString = "222";
return outputString;
}
public static void main(String[] args) {
System.out.println(formatNumberWithSpaces("123 222 2222"));
}
}
thanks for the help, and sorry for bad english :).
There are many possible ways to solve your problem.
You can do it in an OO way with StringBuilder:
public static String formatNumberWithSpaces(String inputString) {
StringBuilder output = new StringBuilder();
for (char c : inputString.toCharArray()) // Iterate over every char
if (c != ' ') // Get rid of spaces
output.append(c).append(' '); // Append the char and a space
return output.toString();
}
Which you can also do with a String instead of the StringBuilder by simply using the + operator instead of the .append() method.
Or you can do it a more "modern" way by using Java 8 features - which in my opinion is fun doing, but not the best way - e.g. like this:
public static String formatNumberWithSpaces(String inputString) {
return Arrays.stream(input.split("")) // Convert to stream of every char
.map(String::trim) // Convert spaces to empty strings
.filter(s -> !s.isEmpty()) // Remove empty strings
.reduce((l, r) -> l + " " + r) // build the new string with spaces between every character
.get(); // Get the actual string from the optional
}
Just try something that works for you.
Try out this function:
public static String formatNumberWithSpaces(String inputString){
String outputString = ""; //Declare an empty String
for (int i = 0;i < inputString.length(); i++){ //Iterate through the String passed as function argument
if (inputString.charAt(i) != ' '){ //Use the charAt function which returns the char representation of specified string index(i variable)
outputString+=inputString.charAt(i); //Same as 'outputString = outputString + inputString.charAt(i);'. So now we collect the char and append it to empty string
outputString+=' '; //We need to separate the next char using ' '
} //We do above instruction in loop till the end of string is reached
}
return outputString.substring(0, outputString.length()-1);
}
Just call it by:
System.out.println(formatNumberWithSpaces("123 222 2222"));
EDIT:
Or if you want to ask user for input, try:
Scanner in = new Scanner(System.in);
System.out.println("Give me your string to parse");
String input = in.nextLine(); //it moves the scanner position to the next line and returns the value as a string.
System.out.println(formatNumberWithSpaces(input)); // Here you print the returned value of formatNumberWithSpaces function
Don't forget to import, so you will be able to read user input :
import java.util.Scanner;
There are various ways to read input from the keyboard, the java.util.Scanner class is one of them.
EDIT2:
I changed:
return outputString;
..to: return outputString.substring(0, outputString.length()-1);
Just because outputString+=' '; was also appending empty space at the end of string, which is useless. Didn't add an if inside for loop which wouldn't add space when last char is parsed, just because of its low performance inside for loop.
use this code.
public class StringComEspaços {
public static void main(String[] args) {
System.out.println(formatNumberWithSpaces("123 222 2222"));
}
private static String formatNumberWithSpaces(String string) {
String lineWithoutSpaces = string.replaceAll("\\s+", "");
String[] s = lineWithoutSpaces.split("");
String os = "";
for (int i = 0; i < s.length; i++) {
os = os + s[i] + " ";
}
return os;
}
}

Sort a single String in Java

Is there a native way to sort a String by its contents in java? E.g.
String s = "edcba" -> "abcde"
toCharArray followed by Arrays.sort followed by a String constructor call:
import java.util.Arrays;
public class Test
{
public static void main(String[] args)
{
String original = "edcba";
char[] chars = original.toCharArray();
Arrays.sort(chars);
String sorted = new String(chars);
System.out.println(sorted);
}
}
EDIT: As tackline points out, this will fail if the string contains surrogate pairs or indeed composite characters (accent + e as separate chars) etc. At that point it gets a lot harder... hopefully you don't need this :) In addition, this is just ordering by ordinal, without taking capitalisation, accents or anything else into account.
No there is no built-in String method. You can convert it to a char array, sort it using Arrays.sort and convert that back into a String.
String test= "edcba";
char[] ar = test.toCharArray();
Arrays.sort(ar);
String sorted = String.valueOf(ar);
Or, when you want to deal correctly with locale-specific stuff like uppercase and accented characters:
import java.text.Collator;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Locale;
public class Test
{
public static void main(String[] args)
{
Collator collator = Collator.getInstance(new Locale("fr", "FR"));
String original = "éDedCBcbAàa";
String[] split = original.split("");
Arrays.sort(split, collator);
String sorted = "";
for (int i = 0; i < split.length; i++)
{
sorted += split[i];
}
System.out.println(sorted); // "aAàbBcCdDeé"
}
}
In Java 8 it can be done with:
String s = "edcba".chars()
.sorted()
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
A slightly shorter alternative that works with a Stream of Strings of length one (each character in the unsorted String is converted into a String in the Stream) is:
import java.util.stream.Collectors;
import java.util.stream.Stream;
String sorted =
Stream.of("edcba".split(""))
.sorted()
.collect(Collectors.joining());
Convert to array of chars → Sort → Convert back to String:
String s = "edcba";
char[] c = s.toCharArray(); // convert to array of chars
java.util.Arrays.sort(c); // sort
String newString = new String(c); // convert back to String
System.out.println(newString); // "abcde"
A more raw approach without using sort Arrays.sort method.
This is using insertion sort.
public static void main(String[] args){
String wordSt="watch";
char[] word=wordSt.toCharArray();
for(int i=0;i<(word.length-1);i++){
for(int j=i+1;j>0;j--){
if(word[j]<word[j-1]){
char temp=word[j-1];
word[j-1]=word[j];
word[j]=temp;
}
}
}
wordSt=String.valueOf(word);
System.out.println(wordSt);
}
String a ="dgfa";
char [] c = a.toCharArray();
Arrays.sort(c);
return new String(c);
Note that this will not work as expected if it is a mixed case String (It'll put uppercase before lowercase). You can pass a comparator to the Sort method to change that.
Procedure :
At first convert the string to char array
Then sort the array of character
Convert the character array to string
Print the string
Code snippet:
String input = "world";
char[] arr = input.toCharArray();
Arrays.sort(arr);
String sorted = new String(arr);
System.out.println(sorted);
str.chars().boxed().map(Character::toString).sorted().collect(Collectors.joining())
or
s.chars().mapToObj(Character::toString).sorted().collect(Collectors.joining())
or
Arrays.stream(str.split("")).sorted().collect(Collectors.joining())
Question: sort a string in java
public class SortAStringInJava {
public static void main(String[] args) {
String str = "Protijayi";
// Method 1
str = str.chars() // IntStream
.sorted().collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString();
System.out.println(str);
// Method 2
str = Stream.of(str.split(" ")).sorted().collect(Collectors.joining());
System.out.println(str);
}
}
A solution that uses the Stream API and also handles Unicode supplementary characters:
public static String sort(final String s) {
return s.codePoints()
.sorted()
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
}
You can also write up a counting sort algorithm to sort all the characters in an array if you would like to reduce your worst-case time complexity from nlogn to n
public static void main(String[] args) {
String str = "helloword";
char[] arr;
List<Character> l = new ArrayList<Character>();
for (int i = 0; i < str.length(); i++) {
arr = str.toCharArray();
l.add(arr[i]);
}
Collections.sort(l);
str = l.toString();
System.out.println(str);
str = str.replaceAll("\\[", "").replaceAll("\\]", "")
.replaceAll("[,]", "");
System.out.println(str);
}
Without using Collections in Java:
import java.util.Scanner;
public class SortingaString {
public static String Sort(String s1)
{
char ch[]=s1.toCharArray();
String res=" ";
for(int i=0; i<ch.length ; i++)
{
for(int j=i+1;j<ch.length; j++)
{
if(ch[i]>=ch[j])
{
char m=ch[i];
ch[i]=ch[j];
ch[j]=m;
}
}
res=res+ch[i];
}
return res;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("enter the string");
String s1=sc.next();
String ans=Sort( s1);
System.out.println("after sorting=="+ans);
}
}
Output:
enter the string==
sorting
after sorting== ginorst

Categories