How do I reverse all Strings in my array? - java

How do I reverse my array output? Like "peter" to "retep" or "max" to "xam"
I tried to use collections but it's not working
This is my code:
import java.util.Scanner;
import java.util.Collections;
public class sdf {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
String[] my_friend_names = new String[10];
for (int i = 0; i < my_friend_names.length; i++) {
my_friend_names[i] = input.nextLine();
}
for(int i = 0; i < my_friend_names.length; i++) {
System.out.println("Name: " + my_friend_names[i]);
}
Collections.reverse(input);
System.out.println("After Reverse order: " +input);
}
}

Seems you create a string array, but than proceed to try reverse the input.
If you want to use collections you may do something like this:
List<String> list = Arrays.asList(my_friend_names);
Collections.reverse(list);
System.out.println("After Reverse order: " + list);

Your posted code does not compile, for example you call Collections.reverse() on your scanner variable.
Things that might help you.
You've assumed Collections.reverse() will reverse the Strings within the array - it won't, it simply reverses the order of the Strings, e.g.
Collections.reverse() works on java.util.List not a primitive array, you can use Arrays.toList() if you need it
StringBuilder provides a handle reverse() method
Example, use StringBuilder.reverse() to update replace each item in the array with a reversed String
String[] my_friend_names = { "fred", "alice" };
for (int i = 0; i < my_friend_names.length; i++) {
my_friend_names[i] = new StringBuilder(my_friend_names[i])
.reverse().toString();
}
System.out.println(Arrays.toString(my_friend_names));
Output
[derf, ecila]

You are trying to print out input which is of type Scanner. Try using StringBuilder
Scanner input = new Scanner(System.in);
String[] my_friend_names = new String[10];
for (int i = 0; i < my_friend_names.length; i++) {
my_friend_names[i] = input.nextLine();
String reversedName = new StringBuilder(my_friend_names[i]).reverse().toString();
System.out.println("After reverse: " + reversedName);
}

I think it would be the best way to make a char[] from the String, reverse that char[] and convert it back to a String.
Something like this should do the job:
Scanner input = new Scanner(System.in);
String[] my_friend_names = new String[10];
for (int i = 0; i < my_friend_names.length; i++) {
my_friend_names[i] = input.nextLine();
}
input.close();
for(String name : my_friend_names) {
System.out.println("Name: " + name);
}
for(int i=0; i<my_friend_names.length; i++) {
char[] characters=my_friend_names[i].toCharArray();
List<char[]> reverse=Arrays.asList(characters);
Collections.reverse(reverse);
my_friend_names[i]=new String(characters);
}
System.out.println("After Reverse order: ");
for(String name : my_friend_names) {
System.out.println("Name: " + name);
}
Let me know whether it works (or not)
Happy coding :) -Charlie

Related

How to remove duplicate words in string and display them in same order

This is my program to remove duplicate words in a string using set the program
works fine removing duplicate elements, but the output is not in the correct order
public class Remove_DuplicateIN_String {
public static void main(String a[]) throws IOException {
String a1;//=new String[200];
int i;
InputStreamReader reader=new InputStreamReader(System.in);
BufferedReader in =new BufferedReader(reader);
System.out.println("Enter the String ");
a1=(in.readLine());
System.out.print(a1);
System.out.println("\n");
String words[]=new String[100];
words=a1.split(" ");
System.out.println(words.length);
Set<String> uniq=new HashSet<String>();
for(i=0;i<words.length;i++)
{
uniq.add(words[i]);
}
Iterator it=uniq.iterator();
while(it.hasNext())
{
System.out.print(it.next()+" ");
}
}
}
Enter the String
hi hi world hello a
hi hi world hello a
5
hi a world hello
I want output as hi world hello a
Use LinkedHashSet
It maintains order and avoid duplicates.
Set wordSet = new LinkedHashSet();
Use LinkedHashSet.
It will track order and also avoid duplicates of elements.
Set<String> linkedHashSet = new LinkedHashSet<String>();
If you have already stored elements in array of strings, you can use collection api to addAll into set.
String words[]=a1.split(" ");
Set<String> linkedHashSet=new LinkedHashSet<String>();
linkedHashSet.addAll(Arrays.asList(words));.
package StringPrograms;
import java.util.Scanner;
public class RemoveDuplicateWords {
public static void main(String[] args) {
boolean flag;
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String[] str = input.split(" ");
int count = 0;
String[] out = new String[str.length];
for (int i = 0; i < str.length; i++) {
flag = true;
for (int j = 0; j <count; j++) {
if (str[i].equalsIgnoreCase(out[j])) {
flag = false;
break;
}
}
if (flag) {
out[count] = str[i];
count++;
}
}
for (int k = 0; k < out.length; k++) {
if (out[k] != null)
System.out.print(out[k] + " ");
}
}
}
String noDuplicates = Arrays.asList(startingString.split(" ")).stream()
.distinct()
.collect(Collectors.join(" "));
This approach doesn't handle commas and special characters though.

How can i print my array using Arrays.toString(reverse) without[]

how can i print the result without brackets
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
for(int i=0; i < n; i++){
arr[i] = in.nextInt();
}
int[] reverse =new int[n];
for (int i = 0; i < reverse.length; i++) {
reverse[i]=arr[arr.length-1-i];
}
in.close();
}
}
In java8, you can conveniently do any kind of String output using join, there you will have to do some manual reversing though:
String output = String.join(", ", arr);
You can't change the implementation of Arrays.toString() so you can't print your array like that.
Although, you can assign it to an string variable and then manipulate that string as you desire.
String str = Arrays.toString(reverse);
str = str.substring(1, str.length() - 1);

Input from the console in java

I know this is a basic question but I have been trying hard to find Which method I can use if I have to take 2 {123,456} as the input from console where 2 is the number of inputs to the array and {123,456} are inputs to the array. Should I be using Regex for this since it has { symbols or can it be done by scanner alone??
You can read the array part as String and then strip the curly braces using substring. Convert the String to int and store into an array.
import java.util.Scanner;
public class ReadArray {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int count = read.nextInt();
String arrayLine = read.next();
int array[] = new int[count];
String elements[] = arrayLine.split(",");
elements[0] = elements[0].substring(1);
elements[count-1] = elements[count-1].substring(0, elements[count-1].length()-1);
for (int i=0; i<count; i++) {
array[i] = Integer.parseInt(elements[i]);
}
for (int i : array) {
System.out.println(i);
}
}
}
Input :
2 {123,456}
Output :
123
456
Assuming you have read the input as a string, you can do the following:
String[] inputs = input.split(" ");
int arrayLength = Integer.parseInt(inputs[0]);
String inputStringData = inputs[1].substring(1, inputs[1].length());
String[] arrayElements = inputStringData.split(",");
int[] array = new int[arrayLength];
for(int i=0; i<array.length; i++) {
array[i] = Integer.parseInt(arrayElements[i]);
}

Unable to reverse a String after converting it to String Array

I am trying to convert a String to a String Array using the split method. When I try to individually reverse elements of the array using the reverse method, the reverse method doesn't even show up in Eclipse Code Suggestions. Explicitly using reverse, spurts out an error saying The method reverse() is undefined for the type String.
Please help!
public class Split {
public static void main(String args[]){
String temp;
String names="Apple Banana Cabbage Daffodil";
String[] words = names.split(" ");
for (int i = 0; i < words.length; i++) {
temp = words[i].reverse();
}
}
The compiler message is clear: reverse is not a method of String.
Try:
String reverse = new StringBuilder(words[i]).reverse().toString();
There is no method reverse for type String but you could do it yourself like:
public static void main(String args[]){
String temp;
String names="Apple Banana Cabbage Daffodil";
String[] words = names.split(" ");
String[] reverseWords = new String[words.length];
int counter = words.length - 1;
for (int i = 0; i < words.length; i++) {
reverseWords[counter] = new String(words[i]);
counter--;
}
words = reverseWords;
for(String i : words)
{
System.out.print(" " + i);
}
}
There is no reverse method defined for the String type. You can use Collections#reverse on a List which reverses its elements:
String[] words = names.split(" ");
List<String> wordList = Arrays.asList(words);
Collections.reverse(wordList);
It's because String doesn't have method reverse, you can use StringBuilder instead.
Like:
public static void main(String[] args) {
String temp;
String names = "Apple Banana Cabbage Daffodil";
String[] words = names.split(" ");
for (int i = 0; i < words.length; i++) {
temp = new StringBuilder(words[i]).reverse().toString();
}
}

Converting an ArrayList to an array

I have the following problem... I want to read unknown number of strings from the input. So, I made an arraylist 'words' and added all the strings from the input. Then I wanted to convert this arraylist into simpler String array 'wordsarray'(String[])... As I did that I wanted to check if everything is ok (if words are saved in 'wordsarray') so I
tried to print out the whole array... but it doesn't give me what I wanted... It seems like my code does not work. Where is the problem?
Thanks for your help
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<String> words = new ArrayList<String>();
while(sc.hasNextLine()) {
words.add(sc.nextLine());
}
String[] wordsarray = new String[words.size()];
for(int i = 0; i < words.size(); i++) {
wordsarray[i] = words.get(i);
}
for(int i = 0; i < words.size(); i++) {
System.out.println(wordsarray[i]);
}
}
There is a precooked method to do what you are trying to do:
ArrayList<String> words = new ArrayList<String>();
String[] array = words.toArray(new String[words.size()]);
But your code seems correct, are you sure everything is fetched fine inside the ArrayList?
By your comment I guess that the problem is the fact that you don't place everything inside a loop. This code:
while(sc.hasNextLine()) {
words.add(sc.nextLine());
}
works only once. If you keep inserting words and pressing enter you are already outside the loop because the Scanner already reached a point in which it didn't have any more lines to fetch.
You should do something like:
boolean finished = false;
while (!finished) {
while(sc.hasNextLine()) {
String line = sc.nextLine();
if (line.equals(""))
finished = true;
else
words.add(sc.nextLine());
}
}
}
This works fine for me:
import java.util.*;
public class a
{
public static void main (String [] args) throws Exception
{
Scanner sc = new Scanner(System.in);
List<String> words = new ArrayList<String>();
while(words.size () < 3 && sc.hasNextLine ()) {
String s = sc.nextLine();
System.out.println ("Adding " + s);
words.add(s);
}
String[] wordsarray = words.toArray(new String [] {});
for(int i = 0; i < words.size(); i++) {
System.out.println("Printing ..." + wordsarray[i]);
}
}
}
Output:
java a
1
Adding 1
2
Adding 2
3
Adding 3
Printing ...1
Printing ...2
Printing ...3

Categories