Simple way to repeat a string

“. “.repeat(7) // Seven period-with-space pairs: . . . . . . . New in Java 11 is the method String::repeat that does exactly what you asked for: String str = “abc”; String repeated = str.repeat(3); repeated.equals(“abcabcabc”); Its Javadoc says: /** * Returns a string whose value is the concatenation of this * string repeated … Read more

Java end of file

import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static void main(String[] args) { Scanner line = new Scanner(System.in); int counter = 1; while (line.hasNextLine()) { String line = line.nextLine(); System.out.println(counter + ” ” + line); counter++; } } } Task: Each line will contain a non-empty string. Read … Read more

Unclosed Character Literal error

In Java, single quotes can only take one character, with escape if necessary. You need to use full quotation marks as follows for strings: You also used which I assume should be Note: When making char values (you’ll likely use them later) you need single quotes. For example:

Java: how to initialize String[]?

You need to initialize errorSoon, as indicated by the error message, you have only declared it. String[] errorSoon; // <–declared statement String[] errorSoon = new String[100]; // <–initialized statement You need to initialize the array so it can allocate the correct memory storage for the String elements before you can start setting the index. If you only declare the array (as you did) there is … Read more

How to extract a substring using regex

Assuming you want the part between single quotes, use this regular expression with a Matcher: Example: String mydata = “some string with ‘the data i want’ inside”; Pattern pattern = Pattern.compile(“‘(.*?)'”); Matcher matcher = pattern.matcher(mydata); if (matcher.find()) { System.out.println(matcher.group(1)); } Result: the data i want