Print First N characters in reverse - java

import java.util.Scanner;
public class Hello {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
int N = sc.nextInt();
StringBuilder sb = new StringBuilder(str);
System.out.print(sb.reverse().toString());
}
}
the output should be:-
apple
3
ppa
but I'm getting full string in reverse
elppa
like this

You aren't splitting the string at all in your code. What you need is a .substring(). Since you can't reverse a word after performing the .substring() on a StringBuilder, we'll just create our own reverse method. Try this:
import java.util.Scanner;
public class Hello {
public static void main(String[] args) {
Scanner sc = new Scanner(System. in );
String str = sc.nextLine();
int n = Integer.parseInt(sc.nextLine());
System.out.print(reverse(str.substring(0, n)));
sc.close();
}
public static String reverse(String text) {
return new StringBuilder(text).reverse().toString();
}
}
Using strictly StringBuilder methods (as you requested), you can do:
import java.util.Scanner;
public class SplitReverse {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
int n = Integer.parseInt(sc.nextLine());
StringBuilder sb = new StringBuilder(str);
sb=new StringBuilder(sb.substring(0,n));
System.out.println(sb.reverse());
sc.close();
}
}
However, I would recommend this one:
import java.util.Scanner;
public class SplitReverse {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
int n = Integer.parseInt(sc.nextLine());
StringBuilder sb = new StringBuilder(str.substring(0,n));
System.out.println(sb.reverse());
sc.close();
}
}

Try this code. I solved the same problem, I got it right.
import java.util.Scanner;
public class Hello {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
int N = sc.nextInt();
StringBuilder sb = new StringBuilder(str.substring(0,N));
System.out.print(sb.reverse().toString());
}
}

Related

Java StringBuffer cannot print out apostrophe

I would write a snippet that concats two string(with specific elements) to one. May someone could help me?
My code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String first = sc.nextLine();
String second = sc.nextLine();
StringBuilder builder = new StringBuilder(" ");
for(int i = 0; i < first.length(); i++){
builder.append(first.charAt(i));
builder.append(second.charAt(i));
}
String base = builder.toString();
System.out.println(base);
}
}
Tom,
The problem is that one string is longer than the other one.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String elso = sc.nextLine();
String masodik = sc.nextLine();
String longestString = elso;
String shortestString = masodik;
if (shortestString.length() > longestString.length()){
shortestString = elso;
longestString = masodik;
}
StringBuilder builderem = new StringBuilder(" ");
for(int i = 0; i < shortestString.length(); i++){
builderem.append(shortestString.charAt(i));
builderem.append(longestString.charAt(i));
}
for(int i = shortestString.length(); i < longestString.length(); i++){
builderem.append(longestString.charAt(i));
}
String alapba = builderem.toString();
System.out.println(alapba);
}
}
Please let me know if it is working!

Making a word Scrambler with Math.random

import java.util.Scanner;
public class WordScrambler {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int chosenWord;
String[] words = {"hogwash","Rudolph","yule-log","Eggnog","CandyCane","Christmas","Fruitcake","gingerbread","Krampus","nutcracker"};
System.out.println("Pick a number between 1-10");
chosenWord=in.nextInt();
String a=words[chosenWord].substring(0,words[chosenWord].length()/2);
String b=words[chosenWord].substring(words[chosenWord].length()/2);
String c=b+a;
int x=(int)(Math.random()*(words[chosenWord].length()-1))+1;
String d=c.substring(0, words[chosenWord].length()-x);
String e=c.substring(words[chosenWord].length()-x);
String f=e+d;
System.out.println(f);
}
}
This is what i have so far.
I cant find a way to Scramble it anymore.
Right now the output is for example: Hogwash :shhogwa.
Thats the only word that Scrambles.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int chosenIndex;
String[] words = { "hogwash", "Rudolph", "yule-log", "Eggnog", "CandyCane", "Christmas", "Fruitcake",
"gingerbread", "Krampus", "nutcracker" };
System.out.println("Pick a number between 1-10");
chosenIndex = in.nextInt();
String chosenWord = words[chosenIndex - 1];
System.out.println(chosenWord);
StringBuilder scrambled = new StringBuilder();
List<Character> letters = new ArrayList<Character>();
for (char x : chosenWord.toCharArray()) {
letters.add(x);
}
while (letters.size() != 0) {
int random = (int) (Math.random() * letters.size());
scrambled.append(letters.remove(random));
}
System.out.println(scrambled.toString());
}
use meaningful variable names so its clear what its referring to

JAVA Reversing a string on multiple lines output

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();

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);
}
}

Java scanner array input until end of line

I want to input some integers with space delimiter from console, press Enter and then read them into List. (Initially, I don't know the number of the integers and I don't want to parse strings)
Is it possible?
Use a while loop.
public static void main(final String[] args) {
while(true) {
a = scanner.next();
if (a.equals(""))
break;
b = Integer.parseInt(a);
list.add(b);
or:
public static void main(final String[] args) {
while(true) {
try {
a = scanner.nextInt();
list.add(a);
} catch (Exception e) {
break;
}
You can initialize everything yourself. Just a basis to help you :)
Try this:
import java.util.Scanner;
public class help {
public static void main(final String[] args) {
Scanner scnr = new Scanner(System.in);
while (true) {
if (scnr.hasNextInt() == false)
break;
int a = scnr.nextInt();
System.out.println(a);
}
}}
You'll have to figure out a way to detect an empty line in scanner though. I can't think of a way right now.
Scanner scan = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
int a = 0;
a = scan.nextInt();
scan.close();
int count = String.valueOf(a).length();
for(int i = 0; i< count ; i++){
list.add(Integer.parseInt(String.valueOf(a).substring(i, i+1)));
}
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}

Categories

Resources