How to make output in reverse order using Java language? - java

I am facing a problem taking all the lines from standard input and write them to standard output in reverse order.
That is output each line in the reverse order of input.
Below is my code:
import java.util.Scanner;
public class ReverseOrderProgram {
public static void main(String args[]) {
//get input
Scanner sc = new Scanner(System.in);
System.out.println("Type some text with line breaks, end by
\"-1\":");
String append = "";
while (sc.hasNextLine()) {
String input = sc.nextLine();
if ("-1".equals(input)) {
break;
}
append += input + " ";
}
sc.close();
System.out.println("The current append: " + append);
String stringArray[] = append.split(" strings" + "");
System.out.println("\n\nThe reverse order is:\n");
for (int i = 0; i < stringArray.length; i++) {
System.out.println(stringArray[i]);
}
}
}
When I run my code with sample inputs like below:
Type some text with line breaks, end by "-1":
My name is John.
David is my best friend.
James also is my best friend.
-1
I get the following output:
The current append: My name is John. David is my best friend. James also is my best friend.
The reverse order is:
My name is John. David is my best friend. James also is my best friend.
Whereas, the required output is something like below:
The current append: My name is John. David is my best friend. James also is my best friend.
The reverse order is:
James also is my best friend.
David is my best friend.
My name is John.
Can anyone help me to check what is wrong with my code and fix it?

Try the below Code.
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class ReverseOrderProgram {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Type some text with line breaks, end by\"-1\":");
List<String> list= new LinkedList<String>();
String append = "";
while (sc.hasNextLine()) {
String input = sc.nextLine();
if ("-1".equals(input)) {
break;
}
list.add(input);
}
sc.close();
System.out.println("The current append: " + append);
Collections.reverse(list);
for (String string : list) {
System.out.println(string);
}
}
}
Hope This will help you

Instead of appending the input to the append string you should add the input string to a List and then print it from the bottom or use the Collections.reverse() method and then print it straight

Edit - basically same implementation as previous answers, though uses a for loop:
import java.util.ArrayList;
import java.util.Scanner;
public class ReverseOrderProgram {
public static void main(String args[]) {
//create arraylist for lines
ArrayList<String> lines = new ArrayList<String>();
//get input
Scanner sc = new Scanner(System.in);
System.out.println("Type some text with line breaks, end by \"-1\":");
String append = "";
while (sc.hasNextLine()) {
String input = sc.nextLine();
if ("-1".equals(input)) {
break;
}
lines.add(input);
}
sc.close();
System.out.println("The current append: ");
for(String line : lines){
System.out.print(line + ". ");
}
System.out.println("\n\nThe reverse order is:\n");
for (int i = lines.size()-1; i >=0 ; i--) {
System.out.println(lines.get(i));
}
}
}

1 - 1 way to do it is run loop from backword.
for (int i = stringArray.length; i >=0 ; i++) {
System.out.println(stringArray[i]);
}
2 - Use Collections.reverse() method on list and print it. like
List<String> list = Arrays.asList(stringArray);
Collections.reverse(list );
System.out.println("Modified List: " + list );

You can use a Stack data structure that has LIFO behavior for insert and read of elements. Tha more complete Java Stack implementation is Deque that has the method "descendingOrder" that returns an iterator of elements in reverse order.
Deque deque = new LinkedList();
// We can add elements to the queue in various ways
deque.add("Element 1 (Tail)"); // add to tail
deque.addFirst("Element 2 (Head)");
deque.addLast("Element 3 (Tail)");
deque.push("Element 4 (Head)"); //add to head
deque.offer("Element 5 (Tail)");
deque.offerFirst("Element 6 (Head)");
deque.offerLast("Element 7 (Tail)");
Iterator reverse = deque.descendingIterator();
System.out.println("Iterating over Deque with Reverse Iterator");
while (reverse.hasNext()) {
System.out.println("\t" + reverse.next());
}

You can either use Collections.reverse() as suggested by other answers. But the standard way of reversing is done using Stack. Stack is a LIFO data structure which exactly exhibits your required behaviour. You'll need to push all your results to a Stack and pop it until Stack becomes empty. Something like below snippet will give you an outline.
String input = " Hello \n World \n Here you go";
List<String> inputList = Arrays.asList(input.split("\n"));
Stack<String> myStringStack = new Stack<>();
myStringStack.addAll(inputList); // This is to exhibit your input scenario from user.
while (!myStringStack.isEmpty()) { // While your stack is not empty, keep popping!
System.out.println(myStringStack.pop());
}

Related

Convert array element to a string and print first character?

I need to create an array of strings from user input and print the first letter of each element. I'm aware that I need to convert the array to a string somehow, but unsure how to accomplish this. I was unsuccessful with Arrays.toString
Following is my code:
import java.util.Scanner;
import java.util.Arrays;
class Main{
public static void main(String[] args){
Scanner inp = new Scanner(System.in);
System.out.println("How many names would you like to enter in this array?: ");
int numName = inp.nextInt();
String nameArray[] = new String[numName];
System.out.println("Enter the names: ");
for(int i = 0; i <= nameArray.length; i++){
nameArray[i] = inp.nextLine();
}
System.out.println(nameArray.charAt(0));
}
}
You need to iterate over every String in the Array and then print the first char. You can do this using charAt() and a loop.
for(String str : nameArray) {
System.out.println(str.charAt(0));
}
Or you can use Arrays.stream():
Arrays.stream(nameArray).forEach(e -> System.out.println(e.charAt(0)));
Also just a few problems with your code:
You are going to enter into this problem, because nextInt() does not consume the newline. Add a blank nextLine() call after nextInt()
You are looping until <= array.length which will cause an indexOutOfBounds error. You need to only loop until less than array.length
Just do another iteration over the "nameArray", and get the first character of each array element, and print it.
For example, you can use for-each:
for(String name : nameArray) {
System.out.println(name.charAt(0));
}
Arrays.stream(nameArray).map(s -> s.charAt(0)).forEach(System.out::println);

Print Total Number of Different Words (case sensitive) from a file

**Edit after reviewing Tormod's answer and implementing his advice.
As the title states I'm attempting to print the total number of different words after receiving a file name from command line input. I receive the following message after attempting to compile the program:
Note: Project.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Here is my code. Any help is greatly appreciated:
import java.lang.*;
import java.util.*;
import java.io.*;
public class Project {
public static void main(String[] args) throws IOException {
File file = new File(args[0]);
Scanner s = new Scanner(file);
HashSet lib = new HashSet<>();
try (Scanner sc = new Scanner(new FileInputStream(file))) {
int count = 0;
while(sc.hasNext()) {
sc.next();
count++;
}
System.out.println("The total number of word in the file is: " + count);
}
while (s.hasNext()) {
String data = s.nextLine();
String[] pieces = data.split("\\s+");
for (int count = 0; count < pieces.length; count++)
{
if(!lib.contains(pieces[count])) {
lib.add(pieces[count]);
}
}
}
System.out.print(lib.size());
}
}
I would implement it using a HashSet Add all the words, and read out the size. If you want to make it case insensitive just manipulate all the words to uppercase or something like that. this uses some memory but...
one problem you got with the algorithm is that you do only have one "words". it only holds the words at the same line. so you only count same words at the same line.
HashSet stores strings by their hash value, and thus stores one word only one time.
construction: HashSet lib = new HashSet<>();
inside the loop: if(!lib.contains(word)){lib.add(word);}
check the word count: lib.size()
for(String s : words) {
if(s.equals(word))
count++;
}
You are comparing the words to an empty String, since it's a word it's always gonna be false.
Like Tormod said, the best would be to store the words in a HashSet, as it won't keep duplicates. Then just read out its size.

Separating an unknown amount of hyphens in java?

Good day, guys,
I'm working on a program which requires me to input a name (E.g Patrick-Connor-O'Neill). The name can be composed of as many names as possible, so not necessarily restricted to solely 3 as seen in the example above.But the point of the program is to return the initials back so in this case PCO. I'm writing to ask for a little clarification. I need to separate the names out from the hyphens first, right? Then I need to take the first character of the names and print that out?
Anyway, my question is basically how do I separate the string if I don't know how much is inputted? I get that if it's only like two terms I would do:
final String s = "Before-After";
final String before = s.split("-")[0]; // "Before"
I did attempt to do the code, and all I have so far is:
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
String[] x = input.split("-");
int u =0;
for(String i : x) {
String y = input.split("-")[u];
u++;
}
}
}
I'm taking a crash course in programming, so easy concepts are hard for me.Thanks for reading!
You don't need to split it a second time. By doing String[] x = input.split("-"); you have an Array of Strings. Now you can iterate over them which you already do with the enhanced for loop. It should look like this
String[] x = input.split("-");
String initials = "";
for (String name : x) {
initials += name.charAt(0);
}
System.out.println(initials);
Here are some Java Docs for the used methods
String#split
String#charAt
Assignment operator +=
You can do it without splitting the string by using String.indexOf to find the next -; then just append the subsequent character to the initials:
String initials = "" + input.charAt(0);
int next = -1;
while (true) {
next = input.indexOf('-', next + 1);
if (next < 0) break;
initials += input.charAt(next + 1);
}
(There are lots of edge cases not handled here; omitted to get across the main point of the approach).
In your for-each loop append first character of all the elements of String array into an output String to get the initials:
String output = "";
for(String i : x) {
output = output + y.charAt(0);
}
This will help.
public static void main(String[] args) {
String output = "";
String input = "Patrick-Connor-O'Neil-Saint-Patricks-Day";
String[] brokenInput = input.split("-");
for (String temp : brokenInput) {
if (!temp.equals(""))
output = output + temp.charAt(0);
}
System.out.println(output);
}
You could totally try something like this (a little refactor of your code):
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = "";
System.out.println("What's your name?");
input = scan.nextLine();
String[] x = input.split("-");
int u =0;
for(String i : x) {
String y = input.split("-")[u];
u++;
System.out.println(y);
}
}
}
I think it's pretty easy and straightforward from here if you want to simply isolate the initials. If you are new to Java make sure you use a lot of System.out since it helps you a lot with debugging.
Good coding.
EDIT: You can use #Mohit Tyagi 's answer with mine to achieve the full thing if you are cheating :P
This might help
String test = "abs-bcd-cde-fgh-lik";
String[] splitArray = test.split("-");
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < splitArray.length; i++) {
stringBuffer.append(splitArray[i].charAt(0));
}
System.out.println(stringBuffer);
}
Using StringBuffer will save your memory as, if you use String a new object will get created every time you modify it.

Am I overcomplicating a simple solution in Java?

For my Java homework I need to create a script that returns the first word within a string, and, as a part two, I need to also return the second word. I'm currently working on the first part, and I think I'm close, but I'm also wondering if I am over complicating my code a bit.
public static void statements(){
Scanner userInput = new Scanner(System.in);
char [] sentenceArray;
String userSentence;
char sentenceResult;
System.out.print("Enter a complete sentence: ");
userSentence = userInput.nextLine();
for(int x = 0; x < userSentence.length(); x++){
sentenceResult = userSentence.charAt(x);
sentenceArray = new char[userSentence.length()];
sentenceArray[x] = sentenceResult;
if(sentenceArray[x] != ' '){
System.out.print(sentenceArray[x]);
//break; This stops the code at the first letter due to != ' '
}
}
}
I think I've nearly got it. All I need to get working, for the moment, is the for loop to exit once it recognizes there is a space, but it prints out the entire message regardless. I'm just curious if this can be done a little simpler, as well as maybe a hint of what I could do instead, or how to finish.
Edit: I was able to get the assignment completed by using the split method. This is what it now looks like
public static void statements(){
Scanner userInput = new Scanner(System.in);
String userSentence;
System.out.print("Enter a complete sentence: ");
userSentence = userInput.nextLine();
String [] sentenceArray = userSentence.split(" ");
System.out.println(sentenceArray[0]);
System.out.println(sentenceArray[1]);
}
}
As it is your homework, I would feel bad to give you code and resolve it for you.
Seems like you really overcomplicated that, and you are aware, so it's good sign.
I need to create a script that returns the first word within a string,
and, as a part two, I need to also return the second word
So, you have a String object, then check yourself the methods of that class.
It is possible to solve it in 2 lines of code, but:
you must be aware of one special method of String class, the most useful will be one that could somehow split the string for you
you need to have some knowledge about java regular expressions - words are separated by space
after you split the string, you should get an array, accessing first and second element by index of an array will be sufficient
Personally, I think you are overthinking it. Why not read in the whole line and split the string by whitespaces? This isn't a complete solution, just a suggestion for how you can get the words.
public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a complete sentence: ");
try {
String userSentence = reader.readLine();
String[] words = userSentence.split(" ");
System.out.println(words[0]);
System.out.println(words[1]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Here's how I'd do it. Why not return all the words?
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Add something descriptive here.
* User: MDUFFY
* Date: 8/31/2017
* Time: 4:58 PM
* #link https://stackoverflow.com/questions/45989774/am-i-over-complicating-a-simple-solution
*/
public class WordSplitter {
public static void main(String[] args) {
for (String arg : args) {
System.out.println(String.format("Sentence: %s", arg));
List<String> words = getWords(arg);
System.out.println(String.format("# words : %d", words.size()));
System.out.println(String.format("words : %s", words));
}
}
public static List<String> getWords(String sentence) {
List<String> words = new ArrayList<>();
if ((sentence != null) && !"".equalsIgnoreCase(sentence.trim())) {
sentence = sentence.replaceAll("[.!?\\-,]", "");
String [] tokens = sentence.split("\\s+");
words = Arrays.asList(tokens);
}
return words;
}
}
When I run it with this input on the command line:
"The quick, agile, beautiful fox jumped over the lazy, fat, slow dog!"
Here's the result I get:
Sentence: The quick, agile, beautiful fox jumped over the lazy, fat, slow dog!
# words : 12
words : [The, quick, agile, beautiful, fox, jumped, over, the, lazy, fat, slow, dog]
Process finished with exit code 0

Search for a word in a file results in java.util.NoSuchElementException

This is my code. It produces the error java.util.NoSuchElementException.
It is meant to search a file, example.txt for a word (eg. and) and find all instances of the the word and print the word either side of it also (eg. cheese and ham, tom and jerry) in ONE JOptionPane. Code:
import java.io.File;
import java.util.Arrays;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class openFileSearchWord {
public static void main(String Args[])
{
int i=0,j=0;
String searchWord = JOptionPane.showInputDialog("What Word Do You Want To Search For?");
File file = new File("example.txt");
try
{
Scanner fileScanner = new Scanner(file);
String[] array = new String[5];
String[] input = new String[1000];
while (fileScanner.hasNextLine())
{
for(i=0;i<1000;i++)
{
input[i] = fileScanner.next();
if(input[i].equalsIgnoreCase(searchWord))
{
array[j] = input[i-1] + input[i] + input[i+1];
j++;
}
}
}
Arrays.toString(array);
JOptionPane.showMessageDialog(null, array);
fileScanner.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
It looks like you're assuming each line will have 1000 words.
while (fileScanner.hasNextLine())
{
for(i=0;i<1000;i++) <-------- Hardcoded limit?
{
....
}
}
You can try putting another catch loop, or check hasNext() during that for loop.
while (fileScanner.hasNextLine())
{
for(i=0;i<1000 && fileScanner.hasNext();i++)
{
....
}
}
There are also many issues with your code, like if input[i-1] hits the -1 index, or if your 'array' array hits the limit.
I took the liberty to have some fun.
Scanner fileScanner = new Scanner(file);
List<String> array = new ArrayList<String>();
String previous, current, next;
while (fileScanner.hasNext())
{
next = fileScanner.next()); // Get the next word
if(current.equalsIgnoreCase(searchWord))
{
array.add( previous + current + next );
}
// Shift stuff
previous = current;
current = next;
next = "";
}
fileScanner.close();
// Edge case check - if the last word was the keyword
if(current.equalsIgnoreCase(searchWord))
{
array.add( previous + current );
}
// Do whatever with array
....
I see a few error here ...
You are creating two arrays one with 5 and one with 1000 elements.
In your code you are referencing elements directly by index ... but this index might not be present.
input[i-1] ... what if i = 0? ...index is -1
array[j] ... what if j > 4 ... index 5 doesn't exist
I suggest using List of elements instead of fixed arrays.
List<String> array = new ArrayList<>();
You are assuming that the input is something but don't do anything to check what it actually is.
Just as Drejc told you, The first iteration would fail because of the negative index and the program will fail as well if it finds more than 5 matches of the desired word.
Also I want to add another one. You should think that when you do this line:
array[j] = input[i-1] + input[i] + input[i+1];
You have not assigned input[i+1] yet. In that iteration you've just assigned input[i], but no the next one.
You should process the concatenation of the three elements (previousWord + match + nextWord) when reaching nextWord.
Another solution, but inefficient, would be copying all the words to an Array at beginning and using your actual code without modifying. This would work, but you would go twice through all the words.

Categories

Resources