I'm trying to produce a program that outputs the user's input in a form like this:
input: word
w
wo
wor
word
This incremental build-up doesn't seem to be working.
import java.util.*;
public class SpellMan {
public static void main(String[] args) {
Scanner kb = new Scanner (System.in) ;
System.out.println("Give me a word > ");
String word = kb.nextLine();
for(int i = 0; i< word.length();i++){
String bword += ""+word.charAt(i);
System.out.println(bword);
}
}
}
You are declaring bword inside the loop, so in each iteration you attempt to concatenate the current character to an uninitialized String variable.
Try :
String bword = "";
for(int i = 0; i< word.length();i++) {
bword += word.charAt(i);
System.out.println(bword);
}
That said, using a StringBuilder would be more efficient (less objects will be created).
StringBuilder bword = new StringBuilder(word.length());
for(int i = 0; i< word.length();i++) {
bWord.append(word.charAt(i));
System.out.println(bword.toString());
}
Apart from other code problems, the main point concerning your question header is that you can not use += operator within the declaration, because bword is still null (It will not compile).
String bword = ""; //before the loop
bword += word.charAt(i);
System.out.println(bword);
Related
this is a lab for class I'm trying to do. Here's the instructions:
Write a program that takes in a line of text as input, and outputs that line of text in reverse. The program repeats, ending when the user enters "Done", "done", or "d" for the line of text.
Ex: If the input is:
"Hello there
Hey
done"
the output is:
"ereht olleH
yeH"
And here's what I have right now:
public class LabProgram {
public static void main(String[] args) {
/* Type your code here. */
Scanner scnr = new Scanner(System.in);
String[] inputs = new String[100];
String input;
int i = 0;
while (true) {
input = scnr.nextLine();
if(input.equals("Done") || input.equals("done") || input.equals("d"))
break;
inputs[i] = input;
i++;
}
for (int j = 0; j < i; j++) {
int length = inputs[j].length();
String reverse = "";
for (int k = length - i; k >= 0; k--) {
reverse = reverse + inputs[j].charAt(k);
}
System.out.print("\n" + reverse);
}
}
}
Current output
What am I doing wrong??
Iterate through the array, and reverse elements at every index.
This solution is time consuming but does your job
for (int j = 0; j < inputs.lenght; j++) {
int length = inputs[j].length();
char a;
String rev = "";
for(int i =0; i< length; i++){
a = inputs[j].charAt(i);
rev = a + rev;
}
System.out.println(rev);
}
*Try to use StringBuilder And use method reverse -- #Artur Todeschini
To add to what Artur said, an ArrayList of StringBuilders could do the trick quite well:
for(StringBuilder nextEntry : stringBuilderList)
{
nextEntry.reverse();
}
The enhanced for-loop will go through each entry in the ArrayList, and the StringBuilder's reverse will change the order of the letters.
EDIT TO SHOW FORMATTING
ArrayList<StringBuilder> stringBuilderList= new ArrayList<>();
*note. given that this is for a lab, its probably for learning purposes and using built-in classes that does all the work for you are usually not the intended solution. -- #experiment unit 1998X
Try to use StringBuilder
And use method reverse
This is another "ArrayList and StringBuilder-less" version.
Create two Strings, one filled and one empty:
String nextString = stringArray[i],
template = new String();
Loop through the length of the String, adding the next character in from the end each time through.
int length = nextString.length() - 1;
for(int j = 0; j < length; j++)
{
template += nextString.charAt(length - j);
}
Add the whole String to the String array's index
stringArray[i] = template;
NOTE
This is an inner loop for a String array and is NOT complete code
I am creating a program in which a user enters a string of words (Ex: I love you), and the program returns an array of the words in the string spelled backwards (Ex: I evol ouy). However, I cannot get my code to properly compile, and tried debugging, but cannot see where the problem is.
I tried to look for similar problems here on Slack, but the problems are found were concerned with rearranging words from a string, (ex: you I love), and I cannot find a problem similar to mine, involving turning string into an Array and then manipulating the array.
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string to see it in reverse: ");
String userEntry = sc.nextLine();
char[] entryToChar = userEntry.toCharArray();
System.out.println(Arrays.toString(entryToChar));
String[] splitInput = userEntry.split(" ");
String reverseWord = "";
int temp;
String[] reverseString = new String[splitInput.length];
for (int i = 0; i < splitInput.length; i++)
{
String word = splitInput[i];
for (int j = word.length()-1; j >= 0; j--)
{
reverseWord = reverseWord + word.charAt(j);
}
for (int k = 0; k < splitInput.length; k++) {
temp = splitInput[i];
splitInput[i] = reverseWord[j];
reverseWord[j] = temp;
}
} System.out.println("Your sttring with words spelled backwards is " + reverseWord[j]);
I am avoiding using the 'StringBuilder' method as I have not yet studied it, and trying to see if I can get the new string using swapping, as in the code below:
temp = splitInput[i];
splitInput[i] = reverseWord[j];
reverseWord[j] = temp;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String word, reverseWord;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string to see it in reverse: ");
String userEntry = sc.nextLine();
userEntry: I love you
String[] splitInput = userEntry.split(" ");
splitInput: [I, love, you]
for (int i = 0; i < splitInput.length; i++)
{
word = splitInput[i];
reverseWord = "";
for (int j = word.length()-1; j >= 0; j--)
{
reverseWord = reverseWord + word.charAt(j);
}
splitInput[i] = reverseWord;
}
splitInput: [I, evol, uoy]
System.out.println("Your string with words spelled backwards is: " + String.join(" ", splitInput));
}
}
Your string with words spelled backwards is: I evol uoy
Your code is not getting compiled because tmp variable is declared as int while splitInput[i] is String.
The other problem is variable j is outside its block scope from where you are trying to access.
Make your logic clear before writing code to achieve correct result.
A good Java programmer should know which tools exist in the language and make use of them in her/his design appropriately. I would suggest to use the class StringBuilder, which has a method for reversing the string. Your program could look like this:
while in.hasNext() {
StringBuilder sb = in.next();
sb.reverse();
System.out.println(sb.toString());
}
If you want to write the reverse function yourself for practice then you can simply define a method that takes a string and returns a reversed string and call that method in place of sb.reverse().
Please know that String in Java is an immutable object. You cannot modify it directly. You can have modified copies returned.
StringBuilder on the other hand allows the programmer to modify the object directly as you can see in the code above.
You need to split original string into an array and then reverse each one and insert into the new array, here you can use StringBuilder as good practice.
class Testarray{
public static void main(String args[]){
String str = "I am Engineer";
String[] spArray = str.split(" ");
String farr[] = new String[spArray.length];
for(int i=0;i<spArray.length;i++){
String split = spArray[i];
farr[i]=reverseString(split);
}
for(int i=0;i<farr.length;i++){
System.out.println(farr[i]);
}
}
public static String reverseString(String str){
char ch[]=str.toCharArray();
String rev="";
for(int i=ch.length-1;i>=0;i--){
rev+=ch[i];
}
return rev;
}
}
There are a few things going on here, and I think in some places you're mixing up between strings and arrays.
Let's try to break this problem down into smaller problems.
First, we need to reverse a single word. Your first inner loop (the one that uses j) does that, so let's extract it into its own method:
public static String reverseWord(String word) {
String reverseWord = "";
for (int j = word.length()-1; j >= 0; j--) {
reverseWord = reverseWord + word.charAt(j);
}
return reverseWord;
}
Although, you should note that concatenating strings like that in a loop isn't great for performance, and using a StringBuilder would probably be faster (although with such a small application, it probably won't be noticeable):
public static String reverseWord(String word) {
StringBuilder reverseWord = new StringBuilder(word.length());
for (int j = word.length()-1; j >= 0; j--) {
reverseWord = reverseWord.append(word.charAt(j));
}
return reverseWord.toString();
}
Once you have that, you can split the input string (like you did), revere each word, and join them back together:
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string to see it in reverse: ");
String userEntry = sc.nextLine();
String[] splitInput = userEntry.split(" ");
for (int i = 0; i < splitInput.length; i++) {
splitInput[i] = reverseWord(splitInput[i]);
}
System.out.println("Your sttring with words spelled backwards is " +
String.join(" ", splitInput));
All you need is to split your original sentence into separate words and use StringBuilder.reverse() to get words in reverse:
public static void main(String... args) {
String str = getSentenceFromConsole();
System.out.println("Your string with words spelled backwards is '" + reversLettersInWords(str) + '\'');
}
private static String getSentenceFromConsole() {
try (Scanner scan = new Scanner(System.in)) {
System.out.print("Enter a string to see it in reverse: ");
return scan.nextLine();
}
}
private static String reversLettersInWords(String str) {
return Arrays.stream(str.split("\\s+"))
.map(word -> new StringBuilder(word).reverse().toString())
.collect(Collectors.joining(" "));
}
i try with your code
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string to see it in reverse: ");
String userEntry = sc.nextLine();
String[] splitInput = userEntry.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < splitInput.length; i++) {
String word = splitInput[i];
for (int j = word.length() - 1; j >= 0; j--) {
sb.append(word.charAt(j));
}
sb.append(" ");
}
System.out.println("Your sttring with words spelled backwards is " + sb.toString());
here i remove all access line of code....
String input = "i love you";
StringBuilder input1 = new StringBuilder();
input1.append(input);
input1 = input1.reverse();
System.out.println(input1);
You can use this implementation to try to reverse the string elements in the array.
this is a simple program to reverse each word of the string and print ... i dont know whats going wrong with this...please help
import java.util.Scanner;
public class ReverseWordCapitalizeFirstCharacter {
public static void reverse(char a[], int start, int end)
{
while(start<end)
{
char temp = a[start];
a[start] = a[end];
a[end] = temp;
start++;
end--;
}
}
public static void main(String[] args) {
System.out.println("Enter the string");
Scanner sc = new Scanner(System.in);
String str = sc.next();
char a[] = new char[str.length()];
a = str.toCharArray();
int wordStartIndex = 0;
for(int i=0; i<a.length; i++)
{
if(a[i] == ' ')
{
reverse(a,wordStartIndex,i-1);
wordStartIndex = i+1;
}
}
for(int i=0; i<a.length; i++)
{
System.out.print(a[i]);
}
}
}
i am passing the character array as parameter to the function that reverse each word..
Is it not because sc.next() returns only the next word ?
So, you never encounter a ' ' in your string, thus you never call the reverse method. Try with sc.nextLine(); maybe.
Javadoc says :
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
As a result, if you enter "abc 123 456", sc.next() will only return "abc".
String str = sc.next();//str only contains "abc"
[...]
if(a[i] == ' ') //This condition is never met.
You can specify the delimiter like this :
Scanner sc = new Scanner(System.in);
sc.useDelimiter("\n");
Currently I have a method that asks user for an input string but only outputs the first 16 characters! The method is supposed to take in any length of string then output the characters in 4x4 blocks after it does the following: first row remains the same. Shift the second row one position to the left, then shifts the third row two positions to the left. Finally, shift the fourth row three positions to the left. As of now it will only output the first 4x4 block
Also I am not sure how I can change the method so it doesnt ask for user input
I would like it to use a given string like:
String text = shiftRows("WVOGJTXQHUHXICWYYMGHTRKQHQPWKYVGLPYSPWGOINTOFOPMO");
"WVOGJTXQHUHXICWYYMGHTRKQHQPWKYVGLPYSPWGOINTOFOPMO" is the given encrypted string I would like to use. but without asking for user input..I keep getting errors and incorrect outputs..please show how I might fix this
code I am using:
public class shiftRows {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String[] input= new String[4];
String[] output= new String[4];
System.out.println("Enter a String");
String inputStr = sc.next();
for (int i = 0, n = 0; i < 4; i++, n+=4) {
input[i] = inputStr.substring(0+n, 4+n);
}
// -
output[0] = input[0];
for(int i=1; i<4; i++)
{
output[i] = Shift(input[i],i);
}
for(int i=0; i<4; i++)
{
System.out.println(output[i]);
}
}
public static String Shift(String str, int shiftNum)
{
char[] out = new char[4];
if(shiftNum==1)
{
out[0]=str.charAt(1);
out[1]=str.charAt(2);
out[2]=str.charAt(3);
out[3]=str.charAt(0);
}
if(shiftNum==2)
{
out[0]=str.charAt(2);
out[1]=str.charAt(3);
out[2]=str.charAt(0);
out[3]=str.charAt(1);
}
if(shiftNum==3)
{
out[0]=str.charAt(3);
out[1]=str.charAt(0);
out[2]=str.charAt(1);
out[3]=str.charAt(2);
}
return new String(out);
}
}
Here's a good way to do it :
import java.util.Scanner;
public class shiftRows {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String inputStr = "WVOGJTXQHUHXICWYYMGHTRKQHQPWKYVGLPYSPWGOINTOFOPMO";
for (int i = 0 ; i < inputStr.length() ; i++){
System.out.print(inputStr.charAt(i));
if ((i + 1)%4 == 0) System.out.println();
}
}
}
If you want to stock it into a String, just concatenate at each loop and add a "\n" each time the if test is valid.
Cant seem to get this to work. trying to get it to read backwards like a mirror without using the buffer class.
public static void main(String[] args) {
Scanner keyboard = new Scanner(System. in);
System.out.println("Enter a phrase:");
String phrase = keyboard.nextLine();
String Rphrase;
int n = phrase.length();
int r = 0;
do{
n--; r++;
Rphrase[r] = phrase[n];
}while(n >= 0);
System.out.println(Rphrase);
I have provided 4 ways of getting the output of the String reversed.
Option 1:
Just iterate the String backwards.
for (int i=phrase.length()-1; i>-1; i--) {
System.out.print(foo.charAt(i));
}
Option 2:
If you would like to put it in the other buffer you can do:
char[] buffer = new char[phrase.length()];
index = 0;
for (int i=phrase.length()-1; i>-1; i--) {
buffer[index++] = foo.charAt(i);
}
Option 3:
You said you didnt want to use the buffer class (which I think you're referring to StringBuffer so I'm assuming you dont want to use StringBuilder either) so here is how you can do it strictly with Strings (which is rather inefficient, because a new String is constructed each iteration):
String foo = "";
for (int i=phrase.length()-1; i>-1; i--) {
foo += foo.charAt(i);
}
Option 4:
A most likely more efficient way of doing this though, is by using StringBuilder:
StringBuilder sb = new StringBuilder(foo.length());
for (int i=foo.length()-1; i>-1; i--) {
sb.append(foo.charAt(i));
}
String reverse = sb.toString();
OR
Refer to this for very simple String reversal with a StringBuilder:
Reverse a string in Java
Try:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System. in);
System.out.println("Enter a phrase:");
String phrase = keyboard.nextLine();
String rPhrase = "";
for (int i = phrase.length() - 1; i >= 0; i--)
rPhrase += phrase.charAt(i);
System.out.println(rPhrase);
}
This is what you need.
String reverse = "";
String toReverse = "hello";
for(int i = 0; i<toReverse.length();i++){
reverse += toReverse.substring(i,i+1);
}
System.out.println(reverse);
Some hints, rather than a complete solution...
Your loop will run for one more iteration when n = 0, which will lead to trying to access index -1. So perhaps try n > 0 as your condition.
And what would happen if the string is empty? It would also try to access index -1, before ever getting to the loop. Perhaps you should put the condition at the beginning.
String doesn't support the [] operator - try:
Rphrase += phrase.charAt(n);
In which case you may as well get rid of r.
you have to make a decrement so it can read its value back to front
for (int i = name.length() - 1, j = 0; i >= 0; i--, j++) {
newName[j] = name.charAt(i); enter code here
}
System.out.println(newName);
}
Simply use StringBuilder.reverse
str = new StringBuilder(str).reverse().toString();