How do I print content of reference in JAVA? - java

Newbie question comming up. Trying to get my head around JAVA.
How do I print out the content of the reference and not just their postition ? My program is ment to get some text in from the user, and print it out in a reverse order.
Here is my program (so far):
package myProgram;
import javax.swing.JOptionPane;
public class someRandomClass {
public static void main(String[] args) {
String word = JOptionPane.showInputDialog("Write som text here");
StringBuilder outPut = new StringBuilder();
for (int i = word.length()-1; i>=0; i--){
outPut.append(i);
}
System.out.println(outPut.toString());
}
}
I am greatfull for any help and tips! :)

In the line
outPut.append(i);
you are appending the value of your loop counter. You surely mean
outPut.append(word.charAt(i));

You seem to appending the integers instead of the appropriate characters. Try this instead:
outPut.append(word.substring(i, i + 1))
This way, the individual characters of word are appended to your StringBuilder. Note that the append method could also take a char as an argument, so you are also able to use word.charAt(i).

So, you want to emit the character at the position? Try using String.charAt.
outPut.append(word.charAt(i));
I'd probably avoid that and just index the char[] from String.toCharArray, though.
To be honest, I'd avoid doing the reversal loop manually to begin with... try something as follows:
final String word = JOptionPane.showInputDialog("Enter text below");
System.out.println(new StringBuilder(word).reverse());
StringBuilder.reverse should do the work for you (likely in a more efficient way, too). You also don't need to call toString manually, as println will do that for you.

Related

I cannot print value of converted string

I want to reverse a string. I know there are some other methods to do it but I wanted to do in a different way. There is no error but no output when I run my code. I dont understand why "String.valueOf(word.charAt(i)" doesnt return a value? Am I missing something?
String word = "myword";
for (int i = word.length(); i <= 0; i--) {
System.out.print(String.valueOf(word.charAt(i)));
}
The first value of i is out of index. And I also fixed your code. Check below:
String word = "myword";
for(int i=word.length()-1;i>=0;i--){
System.out.print(String.valueOf(word.charAt(i)));}
Just for providing another slightly different solution:
You can use a StringBuilder to reverse a String using its method reverse().
If you have a String, you can use it to initialize the StringBuilder with it and directly reverse it.
This example additionally uses an enhanced for-loop, which always goes through all of the elements. Using that, you can get rid of checking the length of a String and you won't have to use an int i for iterating.
For your requirements, this is a suitable option because you want to reverse the whole String.
String word = "myword";
for (char c : new StringBuilder(word).reverse().toString().toCharArray()) {
System.out.println(c);
}
Note that you can use the reverse() method for printing the reversed word in one line just doing
System.out.println(new StringBuilder(word).reverse().toString());
Your code has 2 issues.
i should be initialized with word.length()-1. Other wise you will get StringIndexOutOfBoundsException
for loop condition should be >= 0.
Below is the corrected code.
String word = "myword";
for(int i=word.length()-1;i>=0;i--) {
System.out.print(word.charAt(i));
}

java method that returns patterned string from range

I'm brand new to Java. I've been assigned a test and I'm stuck on how to complete it. So the case is like so -
Create a method that returns a patterned string from range A000 to ZZZZ. Parameter for the method is string itself, so if we pass A000 it should return A001, if we pass A001 it should return A002 and so on... A009... A999... AA00... AA99... AB00... AB01... AB99... AC00... to AZZZ.
I've been able to increment the numbers, but am unable to change them to letters when they reach 99. Let's say I input AZ99; it should return AZA0, but I don't know how I should write that logic.
I thought of using arrays, but then I'd have to save each iteration of the pattern in the array, and that seems unfeasible. Then I thought I'd use if...else and write the instances where the numbers should increment into letters, but that's unnecessarily long too. I know this can be done by proper logic, but it fails me. I've scrounged multiple threads on stackoverflow, but I can't find one quite like this one.
This is what I've got so far -
public class StringSeries {
public static String returnString (String inputString) {
String newString = inputString.substring(0,2);
String completeNewString = newString +
(Integer.parseInt(inputString.substring(1,inputString.length()))+1);
System.out.println(completeNewString);
return completeNewString;
}
public static void main (String[] args){
Scanner sc = new Scanner();
String inputString = sc.nextLine();
returnString(inputString);
sc.close();
}
}
I need suggestions on how to do this. Also, please elaborate on how a certain logic would work.
Thanks!
P.S. I've looked a lot for this type of question on forums, and haven't been able to find any. I also realize that this question may be repetitive for non-newbies. I request that you don't be rude and point out similar threads if you know where they are. Thanks.
This is much easier than it seems. All you need to do is convert the string to a number in base 36 (Integer.valueOf, Integer.parseUnsignedInt), add one to it, and convert it to an upper case base-36 string (Integer.toString plus converting that to upper case).

How to tokenize a string using indexOf and substring methods

So I have to tokenize a string, and I can only use these 2 methods to tokenize
I have the base, but I don't know what to put in,
My friend did it, but I forgot how it looked, it went something like this
I remember he split it using the length of a tab
public class Tester
{
private static StringBuffer sb = new StringBuffer ("The cat in the hat");
public static void main(String[] args)
{
for(int i = 0; i < sb.length() ; i++)
{
int tempIndex = sb.indexOf(" ", 0);
sb.substring(0,tempIndex);
if(tempIndex > 0)
{
System.out.println(sb.substring(0,tempIndex));
sb.delete(0, sb.length());
}
}
}
}
String.indexOf(int ch) returns the index of a character. If you do sb.indexOf(' ') you'll get the first index of a space. You can use that in conjunction with substring(): sb.substring(0,sb.indexOf(' ')-1) will get you your first token.
This seems like a homework problem, so I don't want to give you the full answer, but you probably can work it out. Comment if you need more help.
If your are familiar with a while loop construct you can take a look at my pseudocode, should be within the constraints of your problem:
String text = "texty text text"
while(TextHasASapce){
print text up to space
set text to equal all text AFTER the space
}
print ??
Using your two allowed methods the above is convertible line by line to what you are after.
Hope it helps.

char Array difficulties

I hope the evening finds you well. My problem tonight is that I'm trying to create a char array, but I can't use any of the good ways to do it. I can only use String.length and String.charAt() my code is a miserable sad mess. This kind of combines all the things I've ever been terrible at so far.
Ultimately what I'll be trying to do is find a way to insert, delete, and replace things given certain indexes of a user-input string, but one step at a time, right?
This is what I have right now for my insert method, it's not even close to done obviously. All I'm really trying to figure out here, is how to print out my array, because when I try to print it out right now its just printing blanks. I apologize for my ineptitude.
public String insert_text(String fromtest){
System.out.println(fromtest.length());
System.out.println(fromtest);
for(int i=0;i<fromtest.length();i++){
text=new char[fromtest.charAt(i)];
System.out.println(text[i]);
}
System.out.println("* Enter the starting position:");
int startpos=k.nextInt();
System.out.println("* Enter the text you want to insert:");
String instring=k.next();
return fromtest;
}
I'm not sure why, but the prompt just say that the only things we can use are Sting.Length and String.charAt and store them to an array which I forgot to mentioned should be private char [] text.
String.toCharArray() is the function that you are looking for. It converts the String into equivalent Char array.
Convert an input String to char[] as the following sample code:
public static void main(String args[])
{
String str = "Sameer";
char[] cArray = str.toCharArray();
//Now perform functions with your charArray
}
Hope this helps.
Why can't you use
char [] input = fromtest.toCharArray(); // get's the character array as called...
if you can't use toCharArray you could try
char [] array = new char[fromtest.length()];
for (int i = 0; i < fromtest.length(); i++) {
array[i] = fromtest.charAt(i);
}
You can print each char by :
System.out.println(fromtest.charAt(i));
public String insert_text(String fromtest){
Char[] charArray = fromtest.toCharArray();
// do whateveryou want;
return fromtest;
}
So far i understand your problem is you need to make dynamic array of what String is passed in this function,
use char[] charArray = string.toCharArray();
but what you are doing i prefer you stack and queues

String Permutations

I was recently trying to write a script that print out all the permutations of a word in Java. For some reason it only prints out one. I just can't figure it out!
import java.util.*;
public class AllPermutations {
ArrayList<String> letters = new ArrayList<String>();
public void main(){
letters.add("H");
letters.add("a");
letters.add("s");
permutate("",letters);
}
public void permutate(String word, ArrayList<String> lettersLeft){
if(lettersLeft.size()==0){
System.out.println(word);
}else{
for(int i=0;i<lettersLeft.size();i++){
String newWord = new String();
newWord = word+lettersLeft.get(i);
lettersLeft.remove(i);
permutate(newWord, lettersLeft);
}
}
}
}
You need to add the letter you have removed back to the lettersLeft list
public void permutate(String word, ArrayList<String> lettersLeft){
if(lettersLeft.size()==0){
System.out.println(word);
}else{
for(int i=0;i<lettersLeft.size();i++){
String temp = lettersLeft.remove(i);
String newWord = word+temp;
permutate(newWord, lettersLeft);
lettersLeft.add(i, temp);
}
}
}
I haven't tested it, but I think it should work.
The problem is that Java/you are passing by reference, not copy (ArrayList). Therefore once you reach the bottom of your recursion tree, lettersLeft will contain 0 elements, and once you go back up, it will still have 0 elements.
As a side note, StringBuilder/StringBuffer is better at doing string permutation task, since String is immutable, therefore you are wasting a lot of resource creating new Strings, n! to be exact. The difference between the two StringBuilder/Buffer is up to you to discover.
The reason for that is lettersLeft is being passed by reference always. Once you are removing a letter from lettersLeft, it is being permanently removed. So for the first iteration you have "HAS" printed out. once that finishes, the recursion algorithm backs up a level to make the second iteration, but what do you know?? lettersLeft is empty. so it terminates without passing by the if statement causing it not to get another word or permutation. In order to resolve this, create a local copy, just like you did with newWord. Hope that helps.
In this case you are removing the letters from the Arraylist and it gets empty till it reaches the end of first word.. Then after that list size is always zero...Add the removed letter back to the list...........
I would recommend you to use the below link and find good examples of String Permutations as there are both memory efficient and space efficient solutions of String permutations...
http://www.codingeek.com/java/strings/find-all-possible-permutations-of-string-using-recursive-method/

Categories