JAVA Reversing a string on multiple lines output - java

Why in my program am i getting the output on one single line ? like abc123... I want my output to be printed on multiple lines, same as my inputs..
import java.util.Scanner;
class Reverse
{
public static void main(String args[])
{
String original;
String reverse = "";
Scanner kbd = new Scanner(System.in);
while (kbd.hasNextLine()) {
original = kbd.nextLine();
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- ) {
reverse = reverse + original.charAt(i);
}
}
System.out.println(reverse);
}
}
It should be for example like this :
input: abc
123
...
output:cba
321
...

Here's one way of doing it:
import java.util.Scanner;
class Reverse {
public static void main(String args[])
{
String original;
String reverse = "";
Scanner kbd = new Scanner(System.in);
StringBuilder output = new StringBuilder();
while (kbd.hasNextLine())
{
original = kbd.nextLine();
StringBuilder sb = new StringBuilder(original);
output.append(sb.reverse().toString()).append("\n");
}
System.out.println(output.toString());
}
}
EDIT I noticed that in your question it seems that you only want to print the output after all input has been provided. I've modified the code from my original answer to do this.

import java.io.*;
import java.util.*;
public class reverseString {
public static void main(String[] args) {
String input="";
System.out.println("Enter the input string");
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
input = br.readLine();
char[] try1= input.toCharArray();
for (int i=try1.length-1;i>=0;i--)
System.out.print(try1[i]);
}
catch (IOException e) {
e.printStackTrace();
}
}}

try this:
package stackoverflow;
import java.util.Scanner;
class Reverse
{
public static void main(String args[])
{
String original;
String reverse = "";
Scanner kbd = new Scanner(System.in);
while (kbd.hasNextLine()) {
original = kbd.nextLine();
//befor you add the reversed string add a jump line firs
if(reverse.length()>0)reverse=reverse+"\n";
int length = original.length();
for ( int i = length - 1 ; i >= 0 ; i-- ) {
reverse = reverse + original.charAt(i);
}
}
System.out.println(reverse);
}
}

You should change this part
for ( int i = length - 1 ; i >= 0 ; i-- ) {
reverse = reverse + original.charAt(i);
}
in
for ( int i = length - 1 ; i >= 0 ; i-- ) {
reverse = reverse + original.charAt(i);
}
reverse = reverse + '\n';
This will add new line character.
I have one advice for you - use StringBuilder for new reverse string
Like this:
public static void main(String args[]) {
String original;
StringBuilder sbReverse = new StringBuilder();
Scanner kbd = new Scanner(System.in);
while (kbd.hasNextLine()) {
original = kbd.nextLine();
int length = original.length();
for (int i = length - 1; i >= 0; i--) {
sbReverse.append(original.charAt(i));
}
sbReverse.append('\n');
}
System.out.println(sbReverse.toString());
}
The reason - in Java, strings are immutable.
That mean every time it execute reverse = reverse + original.charAt(i); it will be created a new string in memory.

You're getting the output in a single line because you are using System.out.printf(). Use System.out.println() instead.
PS: an easier way to reverse a string would be to use reverse() from StringBuilder.
reverse = new StringBuilder(original).reverse().toString();

Related

How can I make a java program that takes an input of words, finds certain words, replaces them and then prints out everything again?

I am not sure what to do, I have found all this online and I am trying to change it to do what I explained above but I am stuck. Basically what I want to do is copy and paste an essay into the code somewhere, the have it look through the essay for any words i tell it to look for, and if it finds them then to replace it with the word or words I want it to.
/**
*
import java.util.Arrays;
public class Main {
public static String[] wordList(String line){
return line.split(" ");
}
public static void main(String args[]) {
String words = "test words tesing";
String[] arr = wordList(words);
for(words i=0; i<words.length; i++)
for (String s: arr)
System.out.println(s);
}
}
*/
import java.util.Scanner;
import java.util.Arrays;
public class Main {
public static void main ( String args[] ){
String[] sEnterWord = getSortedWordArr();
showWordlist(sEnterWord);
String sWordToChange = getInputFromKeyboard("Which word would you like to change? ");
System.out.println("You have chosen to change the word : " + sWordToChange);
changeWordInArray(sWordToChange, sEnterWord);
Arrays.sort(sEnterWord);
showWordlist(sEnterWord);
}
private static String[] getSortedWordArr(){
String line = getInputFromKeyboard("How many words are you going to enter? ");
int length = Integer.valueOf(line);
String[] sEnterWord = new String[length];
for(int nCtr = 0; nCtr < length; nCtr++){
sEnterWord[nCtr] = getInputFromKeyboard("Enter word " + (nCtr+1) + ":");
}
Arrays.sort(sEnterWord);
return sEnterWord;
}
private static String getInputFromKeyboard(String prompt){
System.out.print(prompt);
Scanner s = new Scanner(System.in);
String input = s.nextLine();
return input;
}
private static void showWordlist(String[] words){
System.out.println("Your words are: ");
for (String w : words){
System.out.println(w);
}
}
private static void changeWordInArray(String word, String[] array){
String newWord = getInputFromKeyboard("Enter the new word: ");
for (int i = 0; i < array.length; i++){
if (array[i].equals(word)){
array[i] = newWord;
break;
}
}
Arrays.sort(array);
}
}
To read from the keyboard use
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader (isr);
String cadena = br.readLine();
And all the words you introduced form the keyboard will be in "cadena".
To separte all the words you introduced you could use the method split from String.class.
String[] words = cadena.split(" ");
To find a specific word you could use a method and the code would be in your method would be:
String yourWord = "";
for(int i = 0; i < words.length; i++)
{
if(words[i].equals("your word"))
{
yourWord = words[i];
break;
}
}
To replece a word use the method replce(theWord, "the replacement")
You can prints all the words using a loop for with System.out.println(yourWord);

Why is my program not running? Please check

The following program prompts the user to enter a word; reverse the word and print it. I believe my program contains no error but it does not seem to run in eclipse. Please somebody check my code. Thanks!
import java.util.Scanner;
public class reverseWord
{
public static String reverse(String m)
{
String reverse = "";
int Length = m.length();
for(int i = Length-1; i>=0; i=i-1)
{
reverse = reverse + m.charAt(i);
}
return reverse;
}
public static void main(String args[])
{
Scanner keyIn = new Scanner(System.in);
String store = keyIn.nextLine();
reverseWord rw = new reverseWord();
rw.reverse(store);
}
}
Your problem is that you are only returning the reversed String but no printing it out to the console. You should also changed the method to be a non-static method or accessing it using the class name instead of an instance. And class names in java always start with a uppercase letter :) Try something like this:
import java.util.Scanner;
public class ReverseWord {
public String reverse(String m) {
String reverse = "";
int Length = m.length();
for (int i = Length - 1; i >= 0; i = i - 1) {
reverse = reverse + m.charAt(i);
}
return reverse;
}
public static void main(String args[]) {
Scanner keyIn = new Scanner(System.in);
String store = keyIn.nextLine();
ReverseWord rw = new ReverseWord();
String reversedWord = rw.reverse(store);
System.out.println(reversedWord);
}
}

finding string when enter position

I have an array alpha={"A","B","C”} and in console if I enter 0 it should display A(position of A = 0) in same way 1=B and 2=C. I have to achieve this in Java.
I have a similar code, but it returns different output. Can someone suggest me code to get output as in my question.
public class Position{
public static void main(String args[]){
String Alpha = ("abcd");
for (int i = 0 ; i<Alpha .length() ; i++)
if (Alpha .charAt(i) == 'd')
System.out.println(i);
}
}
I have an array alpha={"A","B","C”} and in console if i enter 0 it should display A(position of A = 0)
String[] alpha={"A","B","C"} ;
Then if you want to access element at 0 simply you could do
alpha[0] gives you "A"
String result = alpha[0];
public static void main(String args[]){
String[] alpha= {"A","B","C","D"};
for (int i = 0 ; i < alpha.length ; i++){
if(Integer.valueOf(args[0]) == i){
System.out.println(alpha[i] + " is at position " +i);
}
}
}
You can enter the position in the arguments when you run your java program.
public class Position{
public static void main(String args[]){
String[] alpha={"A","B","C”} ;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //read reading from console
String entered = br.readLine();
int index = Integer.parseInt(entered);
System.out.println(alpha[index]); // This will print out "A" if you enter 0
}
}

Java - string split error

I'm trying to split a string and return each sub-string to an array in Java (easier in c#) but the compiler is not having it. I keep getting an index out of bounds error when I try to call the value of any string in the array indexed higher than 0. Here's the code I'm using:
public class hello {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int setter = 3000;
String num = in.next();
String[] numbers = num.split(" ");
int j = numbers.length;
for (int i =0; i < numbers.length ; i++) {
System.out.println(numbers[i]);
}
System.out.println(j);
Even the length of the array being returned is 1.
As David Wallace said in comments: you should use nextLine from Scanner...
But... why read line to split into int?
public static void main(final String[] args) {
final Scanner in = new Scanner(System.in);
String line = null;
List<List<Integer>> all = new ArrayList<>();
while ((line = in.nextLine()) != null) {
final String[] tokens = line.split(" ");
List<Integer> forOneLine = new ArrayList<>();
for (final String token : tokens) {
try {
final Integer value = Integer.valueOf(token);
forOneLine.add(value);
} catch (final NumberFormatException e) {
// Not an Integer
}
}
all.add(forOneLine);
}
Is it ok now?
Ended up parsing to an integer
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String n = in.nextLine();
int ne = Integer.parseInt(n);
String m = in.nextLine();
String[] numbers = m.split(" ");
System.out.println(n);
System.out.println(m);
for (String string : numbers) {
System.out.println(string);
}
}

java beginner programming, putting strings in char array to filter input

in this code I've been trying to filter the characters in the array with a for-loop to a second array, but am unable to. Could anyone tell me what is exactly wrong with my code?
public class Deel1 {
public static void main(String[] args) {
String zinInvoer = getInput();
String zinUitvoer = filterZin(zinInvoer);
}
static String getInput() {
Scanner scan = new Scanner(System.in);
String zinInvoer = "";
System.out.println("Voer een zin in: ");
if (scan.hasNextLine()) {
zinInvoer = scan.nextLine().trim();
}
if (zinInvoer.equals("")) {
System.out.println("Geen invoer!");
System.exit(0);
}
return zinInvoer;
}
static String filterZin(String zinInvoer) {
String zinUitvoer = "";
char ongefilterd[] = zinInvoer.toCharArray();
String nogFilteren = new String(ongefilterd);
char a = nogFilteren.charAt(97);
for (a = 97; a <= 122; a++) {
a = a += 32;
char gefilterd[] = //second array to be printed
}
System.out.println("Gefilterd: " + zinUitvoer);
return zinInvoer;
}
}
Sorry if it annoys you but I had to translate your variables into english in order to figure out what their purposes were.
First of all, it will always throw an exception when the string is less than 98 letters long because it looks for the 97th letter.
Second, the for loop in "filterZin" will only filter letter # 98, which I am guessing was not your intention.
Also, geFilterd should probably be created outside of the for loop, and in the for loop you (i guess) would want to do
geFilterd[a]=a+32;
a+=32;
Because I couldn't figure out what your overall goal was for this program, I made a version of it that does what I think you were trying to do, but again, I do not know.
import java.util.Scanner;
public class Deel1 {
public static void main(String[] args) {
String phraseInput = getInput();
filterPhrase(phraseInput);
}
static String getInput() {
Scanner scan = new Scanner(System.in);
String phraseInput = "";
System.out.println("Voer een zin in: ");
if (scan.hasNextLine()) {
phraseInput = scan.nextLine().trim();
}
if (phraseInput.equals("")) {
System.out.println("Geen invoer!");
System.exit(0);
}
return phraseInput;
}
static String filterPhrase(String phraseInput) {
String phraseOutput = "";
char onFiltered[] = phraseInput.toCharArray();
String currentFilter = new String(onFiltered);
// for (a = 97; a <= 122; a++) {
// a = a += 32;
// //char filtered[] = //second array to be printed
// }
char[] filtered = new char[26];
for(int i=97;i<=122;i++){
char a = currentFilter.charAt(i);
filtered[i-97]= (char) (a+32);
}
System.out.println("filtered: " + filtered.toString());
return phraseInput;
}
}

Categories

Resources