I'm fairly new to programming. I'm trying to repeat the word in a given string the amount of times by a given number in the same string. I have decided to loop through the string and add each char to a new string to print out but I'm getting an out of index error.
final String string = "Hello";
final int num = 3;
int number = string.length() * num;
String str = "";
for (int i = 0; i < number; i++) {
str += string.charAt(i);
}
System.out.println(str);
Zero-based index
You are getting the error because the value of i is going beyond the last index available in Hello. The last index in Hello is "Hello".length() - 1 whereas the value of i is going beyond this value because of your loop terminating condition:
i < string.length() * num;
By the way, if you want to repeat Hello 3 times, you should do it as
for(int i = 0; i < num; i ++){
System.out.print(string);
}
Demo:
public class Main {
public static void main(String[] args) {
final String string = "Hello";
final int num = 3;
for (int i = 0; i < num; i++) {
System.out.print(string);
}
}
}
String#repeat
With Java 11+, you can do it without using a loop by using String#repeat:
System.out.println(string.repeat(num));
Demo:
public class Main {
public static void main(String[] args) {
final String string = "Hello";
final int num = 3;
System.out.println(string.repeat(num));
}
}
Just keep it simple
String string = "Hello";
int num = 3;
for (int i = 0; i < num; i++) {
System.out.println(string);
}
If you want to have your result in a new String you can just do this :
String string = "Hello";
int num = 3;
String res = "";
for (int i = 0; i < num; i++) {
res += string;
}
System.out.println(res);
Just adding this in here since you stated you're learning.
Java has a StringBuilder class, super easy to use
And according this this induvial class using StringBuilder is incredibly more efficient than concatenate.
StringBuilder vs String concatenation in toString() in Java
Related
Am trying to reverse a string using a method in java, I can fetch all the elements of the string and print them out in order via a loop, my problem is reversing the string such that the first comes last and the last comes first, I tried to find a reverse function to no avail... Here is what I have so far...
private static void palindrome() {
char[] name = new char[]{};
String name1;
System.out.println("Enter your name");
Scanner tim = new Scanner(System.in);
name1 = tim.next();
int len = name1.length();
for (int i = 0; i <= len; ++i) {
char b = name1.charAt(i);
System.out.println(b + " ");
}
}
That loop succeeds in printing out the single characters from the string.
You can use StringBuilder like this:
import java.lang.*;
import java.io.*;
import java.util.*;
class ReverseString {
public static void main(String[] args) {
String input = "Geeks for Geeks";
StringBuilder input1 = new StringBuilder();
// append a string into StringBuilder input1
input1.append(input);
// reverse StringBuilder input1
input1 = input1.reverse();
// print reversed String
System.out.println(input1);
}
}
You can also modify your code to do this:
1 -
for (int i = 0; i <= len; ++i) {
char b = name1[len - i];
System.out.println(b + " ");
}
2 -
for (int i = len; i >= 0; --i) {
char b = name1.charAt(i);
System.out.println(b + " ");
}
Using Java 9 codePoints stream you can reverse a string as follows. This example shows the reversal of a string containing surrogate pairs. It works with regular characters as well.
String str = "𝕙𝕖𝕝𝕝𝕠 𝕨𝕠𝕣𝕝𝕕";
String reversed = str.codePoints()
// Stream<String>
.mapToObj(Character::toString)
// concatenate in reverse order
.reduce((a, b) -> b + a)
.get();
System.out.println(reversed); // 𝕕𝕝𝕣𝕠𝕨 𝕠𝕝𝕝𝕖𝕙
See also: Reverse string printing method
You simply need to loop through the array backwards:
for (int i = len - 1; i >= 0; i--) {
char b = name1.charAt(i);
System.out.println(b + " ");
}
You start at the last element which has its index at the position length - 1 and iterate down to the first element (with index zero).
This concept is not specific to Java and also applies to other data structures that provide index based access (such as lists).
Use the built-in reverse() method of the StringBuilder class.
private static void palindrome() {
String name1;
StringBuilder input = new StringBuilder();
System.out.println("Enter your name");
Scanner tim = new Scanner(System.in);
name1 = tim.next();
input.append(name1);
input.reverse();
System.out.println(input);
}
Added reverse() function for your understanding
import java.util.Scanner;
public class P3 {
public static void main(String[] args) {
palindrome();
}
private static void palindrome() {
char[] name = new char[]{};
String name1;
System.out.println("Enter your name");
Scanner tim = new Scanner(System.in);
name1 = tim.next();
String nameReversed = reverse(name1);
int len = name1.length();
for (int i = 0; i < len; ++i) {
char b = name1.charAt(i);
System.out.println(b + " ");
}
}
private static String reverse(String name1) {
char[] arr = name1.toCharArray();
int left = 0, right = arr.length - 1;
while (left < right) {
//swap characters first and last positions
char temp = arr[left];
arr[left++] = arr[right];
arr[right--] = temp;
}
return new String(arr);
}
}
you can try the build-in function charAt()
private String reverseString2(String str) {
if (str == null) {
return null;
}
String result = "";
for (int i = str.length() - 1; i >= 0; i--) {
result = result + str.charAt(i);
}
return result;
}
public void test(){
System.out.println(reverseString2("abcd"));
}
see also rever a string in java
String reversed = new StringBuilder(originalString).reverse().toString();
I would like to know why this code do not run. Is there something missing?
Count the number of "xx" in the given string. We'll say that overlapping is allowed, so "xxx" contains 2 "xx".
public class Drumkit {
int countXX(String str){
String a = "abcxxx";
int count = 0;
for (int i = 0; i < str.length() - 1; i++) {
if (a.substring(i, i + 2).equals("xx")) count++;
}
return count;
}
}
You are passing str and using its length() in your function. But, in the loop you're using a (local string variable) which seems like a logical mistake.
You need to pass the input string when your call this function and use str (the function argument) to count the matches.
Here's a functional example:
class Test
{
static int countXX( final String str ) {
int count = 0;
for (int i = 0; i < str.length() - 1; i++) {
if (str.substring(i, i + 2).equals("xx")) count++;
}
return count;
}
public static void main (String[] args)
{
final String s = "abcxxx";
final int count = countXX( s );
System.out.println( count );
}
}
Here's the live example: https://ideone.com/Lm6Ir4
Your problem is unclear. however, you can try this code
public static void main(String[] args) {
final int count = countXX("abcxx efjxx xyzxx xx xxxx xx","xx");
System.out.println(count);
}
static int countXX(final String text, final String occurrenceOf){
int count = 0;
int fromIndex=0;
for (int i = 0; i < text.length() - 1; i++) {
int index = text.indexOf(occurrenceOf,fromIndex);
if(index >-1) {
count++;
fromIndex=index+1;
}
}
return count;
}
I have written a piece of code to reverse a string in Java. However, its showing multiple errors and I wish to understand where it is that I am going wrong. I know that there are alternative methods of reversing a string. However, I want to know where I am going wrong with my code.
public class RevString {
public static void main(String[] args)
{
public Reverse (String str)
{
int len = str.length();
String rev;
for (int i = 0; i <= len; i++)
{
rev = str[i] + rev;
}
System.out.println(rev);
}
Reverse("Canyon");
}
}
Errors:
Multiple markers at this line
- Syntax error on token ")", ; expected
- Syntax error on token "(", . expected
- Reverse cannot be resolved to a type
- Illegal modifier for parameter str; only final is
The method Reverse(String) is undefined for the type
RevString
Could someone provide me with a resolution?
There are many errors in your code :
For loop condition should be i < len
String rev should be initialized to "" (empty string), else it will throw error when you try to append another string to it.
You can't access characters in a string using str[i], use str.charAt(i) instead.
You are trying to initialize a function (Reverse) inside another function (main), you must initialize it outside the main function.
Also, here is a simple one liner for string reversal:
new StringBuilder(str).reverse().toString()
A good tip might be to use the StringBuilder class whenever you want to do any kind of string manipulation in Java.
Your code has many issues:
You are declaring the method Reverse() inside the main method.
You also need to initialize rev to an empty string.
You can use str.charAt(i) to access each character of the string.
Your for loop goes beyond the string if you use i <= len; so it
should be i < len;.
Your Reverse() method should be static since you are calling it in main
method (which is static)
Here is working code.
public class RevString {
public static void main(String[] args) {
Reverse("Canyon");
}
public static void Reverse (String str) {
int len = str.length();
String rev="";
for (int i = 0; i < len; i++) {
rev = str.charAt(i) + rev;
}
System.out.println(rev);
}
}
Please see the below code:
public class Hello {
public static String reverse (String str){
int len = str.length();
String rev="";
char[] strArray = str.toCharArray();
for (int i = 0; i < len; i++)
{
rev = strArray[i] + rev;
}
return rev;
}
public static void main(String[] args) {
String result = reverse("Canyon");
System.out.println("Reversed String: " + result);
}
}
public class reverseString
{
public static void main(String[] args)
{
System.out.println("Welcome to the the string reverser.");
System.out.println("Here is where a person may put is a sentence and the orintation" +
" of the words is reversed.");
Scanner keyboard = new Scanner(System.in);
String word = keyboard.nextLine();
int lengthOf = word.length();
int j = 0;
char loopStr;
String LoopStr;
String Nstr = "";
for(int n = lengthOf; n >0 ;n--)
{
j = n;
LoopStr = word.substring(j-1,j);
Nstr = Nstr + LoopStr;
}
System.out.println(Nstr);
}
}
i hope someone can help me, i have the following problem.
I have a variable that looks like this:
var a = "01VENT000KRV010WFEVVV055";
I would like to either:
have the last 3 figures of the variable (e.g. 055) as an int
or remove ALL non-figures out of the variable (e.g. 01000010055) as an int
My idea was that:
int sub = Integer.parseInt(a.substring(a.length-3));
or:
int sub = Integer.parseInt(a.replaceAll("[\\D]", ""));
That didnt work, so i would really appreciate if someone could help me here
Thanks
Note all methods can potentially return an empty string.
public static void main(String[] args) {
// TODO code application logic here
String a = "01VENT000KRV010WFEVVV055";
System.out.println(removeChars(a));
System.out.println(removeDigits(a));
System.out.println(getLastThreeChars(a));
}
//This method removes Characters from a string and returns a String of numbers
static String removeChars(String t)
{
String tempString = "";
for(int i = 0; i < t.length(); i++)
{
if(Character.isDigit(t.charAt(i)))
{
tempString += t.charAt(i);
}
}
return tempString;
}
//This method removes Digits from a string and returns only characters
static String removeDigits(String t)
{
String tempString = "";
for(int i = 0; i < t.length(); i++)
{
if(Character.isAlphabetic(t.charAt(i)))
{
tempString += t.charAt(i);
}
}
return tempString;
}
//This methods prints the last 3 char of a string
static String getLastThreeChars(String t)
{
StringBuilder tempString = new StringBuilder();
for(int i = t.length() - 1; i > t.length() - 1 - 3; i--)
{
tempString.append(t.charAt(i));
}
return tempString.reverse().toString();
}
So I was creating this random string generator:
public class Test {
public static void main(String[] args) {
String strings = "abcdefghijklmnopqrstuvwxyz1234567890!##$%&()ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Random generator = new Random(System.currentTimeMillis());
int stringLength = strings.length()-1;
Character character;
for (int i = 0; i < stringLength; i++) {
Double test = new Double(Math.random());
character = strings.charAt(test.intValue());
String outputString = outputString.concat(character.toString());
}
System.out.println(outputString);
}
}
I went an compiled it using javac Test.java, and it gave me the error outputString might not have been initialised for lines 14 and 16. So I added the String keyword to line 14, and now it's telling me
cannot find symbol: variable outputString
Why is this so?
EDIT:
Okay so I took up the suggestions, and this is the code currently:
public class Test {
public static int randomInt(int min, int max, long seed) {
Random rand = new Random(seed);
int randomNum = rand.nextInt((max-min)+1) - min;
return randomNum;
}
public static void main(String[] args) {
String strings = "abcdefghijklmnopqrstuvwxyz1234567890!##$%&()ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int stringLength = strings.length()-1;
Character character;
for (int i = 0; i < stringLength; i++) {
Double test = new Double(randomInt(0, stringLength, System.currentTimeMillis()));
character = strings.charAt(test.intValue());
System.out.print(character);
}
}
}
The code runs without errors, but it doesn't print anything.
I'm currently using Command Prompt to compile it.
You are defining the outputString only inside of the for loop. It will not be available outside.
You could output the characters directly:
for (int i = 0; i < stringLength; i++) {
Double test = new Double(Math.random());
character = strings.charAt(test.intValue());
System.out.print(character);
}
System.out.println();
If you insist on concatenating a String in a loop, please use StringBuilder instead.
The next problem you will run into:
Double test = new Double(Math.random());
strings.charAt(test.intValue());
That will always get the the first character. The double will be between 0 (inclusive) and 1 (exclusive).
You need to create a random integer between 0 and the length of your alphabet.
The compiler is correctly telling that outputString is not declared correctly. The outputString is declared within the for loop, but you are trying to print the value outside.
A quick way to fix this would be to declare outputString outside the for loop by having outputString = "";
outputString is only defined within the block of the for loop, so once you exit it, it no longer exists. To make sure that your code works, define it outside the loop:
String outputString = "";
for (int i = 0; i < stringLength; i++) {
Double test = new Double(Math.random());
character = strings.charAt(test.intValue());
outputString += character.toString();
}
System.out.println(outputString);
It is because you are calling outputString.concat before you have intialized it
try
String outputString = "";
outputString = outputString.concat(character.toString());`
I managed to get it to work using the following code:
import java.util.Random;
public class Test{
public static void print(String str) {
System.out.print(str);
}
public static int randomInt(int min, int max) {
Random rand = new Random(System.currentTimeMillis());
int randomNum = rand.nextInt((max-min)+1) - min;
return randomNum;
}
public static void main(String[] args) throws InterruptedException {
String strings = "abcdefghijklmnopqrstuvwxyz1234567890!##$%&()ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int len = strings.length() - 1;
StringBuilder outputString = new StringBuilder(len);
for (int i = 0; i < len; i++) {
Double test = new Double(randomInt(0, len));
Integer value = test.intValue();
if (value <= len) {
//print(value.toString()); For testing purposes
outputString.append(strings.charAt(value));
Thread.sleep(1);
}
else {i--;}
}
print(outputString + "\n");
}
}