Write input lines in reverse order - java

Write a Java program that takes all the lines input to standard input and writes them to standard output in reverse order. That is, each line is output in the correct order, but the ordering of the lines is reversed.
I wrote this:
public static void main(String[] args) {
Scanner sc=new Scanner (System.in);
System.out.println("Enter the line");
String a=sc.nextLine();
System.out.println("Enter the line");
String b=sc.nextLine();
System.out.println(b+" "+a);
}
Is this efficient?

As suggested by one of the comments a Deque would be a good data structure to achieve this:
import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Deque deque = new LinkedList<>();
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your lines (Enter exit to continue):");
while(sc.hasNext()) {
String line = sc.next();
if(line.toLowerCase().equals("exit")) {
break;
}
deque.add(line);
}
System.out.println("\n=====Reversed Lines=====\n");
Iterator reverse = deque.descendingIterator();
while (reverse.hasNext()) {
System.out.println(reverse.next());
}
}
}
Try it here!

Related

need a method to read two files and out put the difference using a scanner class

This is what I have so far. I'm not sure where to go from here. I need a method to output the difference in two files
package JwolfrumCh6;
import java.util.*;
import java.io.*;
import java.util.Scanner;
public class JwolfrumCh6 {
public static void main(String[] args) throws FileNotFoundException
{
Scanner console = new Scanner(System.in);
System.out.print("Enter File one Name");
String file1 = console.nextLine();
Scanner input1 = new Scanner(new File(file1));
System.out.print("Enter File two Name");
String file2 = console.nextLine();
Scanner input2 = new Scanner(new File(file2));
}
public static void compareFiles(Scanner input1, Scanner input2) {
while(input1.hasNextLine() || input2.hasNextLine()) {
}
}
}
Call the static method in main and implement below logic in your compareFiles method.
Read all lines of file 1 to an ArrayList
Read all lines of file 2 to another ArrayList
Use removeAll method of ArrayList as shown below to get the differences in each of these files.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class FML {
public static void main(String[] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in);
System.out.print("Enter File one Name");
String file1 = console.nextLine();
Scanner input1 = new Scanner(new File(file1));
System.out.print("Enter File two Name");
String file2 = console.nextLine();
Scanner input2 = new Scanner(new File(file2));
compareFiles(input1, input2);
}
public static void compareFiles(Scanner input1, Scanner input2) {
List<String> list1 = new ArrayList<String>();
List<String> list2 = new ArrayList<String>();
while (input1.hasNextLine()) {
list1.add(input1.nextLine());
}
while (input2.hasNext()) {
list2.add(input2.nextLine());
}
List<String> tmpList = new ArrayList<String>(list1);
tmpList.removeAll(list2);
System.out.println("content from file1 which is different from file2");
for(int i=0;i<tmpList.size();i++){
System.out.println(tmpList.get(i));
}
System.out.println("content from file2 which is different from file2");
tmpList = list2;
tmpList.removeAll(list1);
for(int i=0;i<tmpList.size();i++){
System.out.println(tmpList.get(i));
}
}
}

Java search program

I am trying to make this program that prints out the words that start with a certain letter from a list words. For example if you enter the letter "e" it should only print words that start with the letter "e" but for some reason it is reading words like "far east" even though it does not start with the letter "e". Any suggestions?
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class words {
public static void main(String[] args) throws IOException {
Scanner key = new Scanner(System.in);
File wordfile = new File("wrds.txt");
if(wordfile.exists()){
Scanner keyboard = new Scanner(wordfile);
int counter = 0;
System.out.println("Enter a character");
char wrd = key.next().charAt(0);
while(keyboard.hasNext()) {
String word = keyboard.next();
if(word.startsWith(""+ wrd)) {
counter++;
}
}
System.out.println("Found "+counter+" words that begin with "+ wrd);
}
}
}
By default, scanner breaks words with whitespaces. So 'far east' is scanned as 'far' and 'east'. Use delimiter instead to ignore whitespaces. Refer the code below.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Words {
public static void main(String[] args) throws IOException {
Scanner key = new Scanner(System.in);
File wordfile = new File("wrds.txt");
if(wordfile.exists()){
Scanner keyboard = new Scanner(wordfile);
int counter = 0;
System.out.println("Enter a charycter");
char wrd = key.next().charAt(0);
keyboard.useDelimiter(System.getProperty("line.separator"));
while(keyboard.hasNext()) {
String word = keyboard.next();
if(word.startsWith(""+ wrd)) {
counter++;
}
}
System.out.println("Found "+counter+" words that begin with "+ wrd);
}
}
}

SPOJ Life Universe and Everything

I am trying to solve the below problem on spoj with Java6(JAR):-
Your program is to use the brute-force approach in order to find the Answer to Life, the Universe, and Everything. More precisely... rewrite small numbers from input to output. Stop processing input after reading in the number 42. All numbers at input are integers of one or two digits.
Input:
1
2
88
42
99
Output:
1
2
88
SPOJ is not accepting my solution.I think the below solution has some error. If not, Is there ant special format to write the code on spoj so that my solution will get accepted.
import java.util.*;
class Life
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int arr[] = new int[100];
int a;
for( a=0;a<100;a++)
{
int i = sc.nextInt();
if(i<100)
{
arr[a]=i;
}
if(a>0)
{
if(arr[a-1] > arr[a])
break;
}
}
for(int j=0;j<a;j++)
{
System.out.print(arr[j]);
}
sc.close();
}
}
You didn't understand problem statement perfectly! It is like you have infinite input as integer but stop when you get the input as 42 till that print all the integers you get as an input. So here is the code for it!
import java.util.Scanner;
class Life
{
public static void main(String args[])
{
Scanner sc =new Scanner(System.in);
while(true) //This loop will always run till we break it from inside the loop
{
int ip=sc.nextInt(); //Taking input as an integer
if(ip == 42) //If input is 42 , break the loop
break;
System.out.println(ip); //else print that integer and continue the loop
}
}
}
Accepted Solution of above problem
import java.util.*;
import java.lang.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
ArrayList<Integer> arrayList = new ArrayList();
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()){
int num = Integer.parseInt(scanner.nextLine());
if(num>=0 && num<100){
if(num == 42){
break;
}
arrayList.add(num);
}
}
Iterator itr = arrayList.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Simple Java Solution
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc=new Scanner(System.in);
if (sc.hasNext())
{
while(true)
{
int n=sc.nextInt();
if (n==42)
{
break;
}
System.out.println(n);
}
}
}
}

How do I add elements to a treeset with a loop that takes user input?

I've been trying to add elements to a TreeSet using a loop that accepts user input. The problem I'm running into is that the loop I created is only filling the TreeSet with the first element that the user inputs. I was using all string variables in this example and I was also attempting to use the word 'end' as a sentinel value to terminate the loop and then print out the elements that had been added to the TreeSet. My only problem is not being able to fill the TreeSet with more than the first user input element. This is the code I used:
import java.util.*;
import java.util.Scanner;
public class TestRun {
public static void main(String[] args) {
java.util.TreeSet wordList = new java.util.TreeSet();
Scanner input = new Scanner(System.in);
String word;
System.out.print("Enter a word: ");
wordList.add(input.next());
while(!(word = input.nextLine()).equals("end")){
System.out.print("Enter a word: ");
}
java.util.Iterator iterator = wordList.iterator();
while(iterator.hasNext()){
System.out.print(iterator.next() + " ");
}
System.out.println();
}
}
You're missing a call to wordList.add in your loop:
while(!(word = input.nextLine()).equals("end")){
wordList.add(word); // The call you were missing
System.out.print("Enter a word: ");
}
import java.util.Scanner;
import java.util.TreeSet;
public class largestandSmallestelementinanArray {
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
int size=0;
System.out.println("enter the size of an array");
size = sc.nextInt();
TreeSet tr = new TreeSet();
while(size>0)
{
tr.add(sc.nextInt());
size--;
}
System.out.println(tr);
}
}

Multi-word scanner input in java?

So I'm trying to use if-else statement dependant upon the user's input. It works when the user's input is only one word, however, multiple word inputs go unrecognized and triggers the else statement. How can i resolve this?
import java.util.Scanner;
public class MyFirstJavaClass {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner myScanner = new Scanner(System.in);
String answer;
System.out.println("Catch the tiger or run away?");
answer = myScanner.next();
if (answer.equals("Catch the tiger" )) {
System.out.println("You've been mauled by a tiger! What were you thinking?");
answer = myScanner.next();
} else {
System.out.println("run away");
}
}
}
Replace:
answer = myScanner.next();
With:
answer = myScanner.nextLine();
next will only read in the next value until it reaches a space or newline. You want to read in the full line before making the comparison
try this :
Scanner scanner = new Scanner(System.in);
int choice = 0;
while (scanner.hasNext()){
if (scanner.hasNextInt()){
choice = scanner.nextInt();
break;
} else {
scanner.next(); // Just discard this, not interested...
}
}
Reference :
Flush/Clear System.in (stdin) before reading
Try this
import java.util.Scanner;
public class MyFirstJavaClass {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner myScanner = new Scanner(System.in);
System.out.println("Catch the tiger or run away?");
if (myScanner.hasNext("Catch the tiger")) {
System.out.println("You've been mauled by a tiger! What were you thinking?");
} else {
System.out.println("run away");
}
}
}

Categories

Resources