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");
}
}
Related
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
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();
}
I'm having trouble with this problem.
Here is the code I wrote out:
package com.jdewey.rvrs;
import java.util.Scanner;
public class Reverse {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Enter your string: ");
String userIn = console.nextLine();
int inLength = userIn.length();
stringRvrs(userIn, inLength);
}
public static void stringRvrs(String x, int length){
for(int i = 1; i <= length; i++){
int y = -1 * i + length;
System.out.print(x.substring(y));;
}
}
}
It's supposed to output "tset" if you were to input "test"
Please help!
It makes more sense to just write your loop to start at the end of the string, and also to print each character using charAt instead of substring. See below:
public static void stringRvrs(String x, int length){
String result = "";
for(int i = length - 1; i >= 0; i--){
result = result + x.charAt(i);
}
System.out.println(result);
}
Of course, there is an easier way using library functions to reverse a string (see here: Reverse a string in Java), but I assume this is a learning exercise for you so I corrected the code instead of just linking to an easy way to do it.
Try StringBuilder as in:
public static void stringRvrs(String x){
char [] all = x.toCharArray();
StringBuilder concate = new StringBuilder();
for(int i = all.length-1;i >= 0;i--){
concate = concate.append(String.valueOf(all[i]));
}
System.out.println(x+" reversed to "+concate);
}
No need to pass int length as an parameter to the method.
you can simply use stringBuilder.reverse();
your method should look like this after the changes,
public static void stringRvrs(String x, int length){
StringBuilder sb = new StringBuilder(x);
System.out.println(sb.reverse());
}
There is no need to pass the length of the String as an argument since it can be found using string.length(); at any point of time.
My main method:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String string1;
string1 = input.next();
LargeInteger firstInt = new LargeInteger(string1);
System.out.printf("First integer: %s \n", firstInt.display());
}
LargeInteger class:
public class LargeInteger {
private int[] intArray;
//convert the strings to array
public LargeInteger(String s) {
for (int i = 0; i < s.length(); i++) {
intArray[i] = Character.digit(s.charAt(i), 10); // in base 10
}
}
//display the strings
public String display() {
String result = "";
for (int i = 0; i < intArray.length; i++) {
result += intArray[i];
}
return result.toString();
}
}
You did not instantiate your array. You need something like:
private int[] intArray = new int[SIZE];
where size is the length of your array.
You are not initialize the array intArray, that way you are getting error, here is the complete program
import java.util.Scanner;
class TestForNull {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String string1;
string1 = input.next();
LargeInteger firstInt = new LargeInteger(string1);
System.out.printf ("First integer: %s \n", firstInt.display());
}
}
and this is LargeInteger
public class LargeInteger {
private int[] intArray;
//convert the strings to array
public LargeInteger(String s) {
intArray = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
intArray[i] = Character.digit(s.charAt(i), 10); // in base 10
}
}
//display the strings
public String display() {
String result="";
for (int i = 0; i < intArray.length; i++) {
result += intArray[i];
}
return result.toString();
}
}
private int[] intArray;
Member variables are null by default, so you need to initialize this.
Most likely you want it the same size as your string:
public LargeInteger(String s) {
intArray = new int[s.length()]; // Create the actual array before you try to put anything in it
for (int i = 0; i < s.length(); i++) {
intArray[i] = Character.digit(s.charAt(i), 10); // in base 10
}
}
Or you should use a container that resizes itself, like ArrayList.
Diferent approach through Integer.parseInt
Integer.parseInt("yourInt");
To achieve your goal:
String a = "12345667788" //sample
String b = "";
int [] vecInt = new int[a.length()]; // The lack of initialization was your mistake as the above stated
for(int i=0; i< a.length(); i++)
{
b = a.substring(0,1);
a= a.substring(1);
vecInt[i] = Integer.parseInt(b);
}
Please be aware of Double, long have far higher range then Integer which might be enough in your case to avoid an array!
you forgot to initialize the array intArray
I would recommend to use a java.util.List
You forgot to initialize the array. You have written it in constructor and the variables declared in method or constructor needs to be initialize at the same time.
Note : Implementing your logic in Constructor is not recommended unless and until you dont have any other choice.