same input calling two different methods in java - java

I'm trying to implement the main method in java for a KWIC. The issue I'm having is that I have to ask the user if they want to write the input from the console/file and write the output to the console/file. The first time asking the user for console/file works fine when I have to read, but when I ask them again for the output I believe it goes back into the first If condition. Here is the code for reference.
try {
System.out.println("Please enter FILE to input from file or CONSOLE to input from console:");
String userInput = "";
while ((userInput = scannerWrapper.nextLine()) != "-1") {
if (userInput.equals("CONSOLE")) {
System.out.println("Please enter FILE to output from file or CONSOLE to output from console:");
List<String> cshiftConsole = circularShifter.shiftLines(inputFromConsole.read());
if (userInput.equals("CONSOLE")) {
System.out.println("Please enter lines to add, then enter -1 to finish:");
// Console
cshiftConsole = alphabetizer.sort(cshiftConsole);
outputToConsole.write(cshiftConsole);
for (String element : cshiftConsole) {
System.out.println(element);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
This is my console output
Please enter FILE to input from file or CONSOLE to input from console:
CONSOLE
Please enter FILE to output from file or CONSOLE to output from console:
CONSOLE
Software Architecture
-1
Please enter lines to add, then enter -1 to finish:
Architecture Software
CONSOLE
Software Architecture
After the second CONSOLE(userInput) I should be asked to enter the lines, But this is taking CONSOLE as the input I want to circularly shift. Any help would be great thank you.

You have some issues in your code, and if I understand correctly you want to decide where to INPUT from, where to OUTPUT to and get a couple of Strings into a List.
(userInput = scannerWrapper.nextLine()) != "-1" You compare Strings in Java using .equals(...) as you did in your code further below.
Every time you're asking your user where he wants to input from, you just have to read it once, so instead of having it inside a while do it on an if.
You create your list on every iteration, have it as an instance member instead.
On every iteration you're printing your objects, wait until the user stops adding items first (they type -1)
A better approach could be like this:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class InputCycle {
private Scanner scanner;
private static final String CONSOLE = "CONSOLE";
private static final String EXIT_CODE = "-1";
private List<String> list;
public static void main(String[] args) {
new InputCycle().readAndWrite();
}
private void readAndWrite() {
scanner = new Scanner(System.in);
list = new ArrayList<String>();
System.out.println("INPUT FROM CONSOLE / FILE");
String input = scanner.nextLine(); // Read where to input from
if (input.equals(CONSOLE)) {
System.out.println("OUTPUT TO CONSOLE / FILE");
String output = scanner.nextLine(); // Read where to output to
if (output.equals(CONSOLE)) {
System.out.println("WRITE LINES (" + EXIT_CODE + " TO EXIT)");
String line = "";
do {
line = scanner.nextLine(); // Read every line
if (!line.equals(EXIT_CODE)) {
list.add(line);
}
} while (!line.equals(EXIT_CODE));
} else { // Write to a file with your own code
System.out.println("Writing to a file");
}
} else { //Read from a file
System.out.println("Reading from a file");
}
System.out.println("ALL LINES: ");
list.forEach(line -> System.out.println(line)); //Print all the lines user wrote
}
}
That has this output:
INPUT FROM CONSOLE / FILE
CONSOLE
OUTPUT TO CONSOLE / FILE
CONSOLE
WRITE LINES (-1 TO EXIT)
FOO
BAR
BANANA
-1
ALL LINES:
FOO
BAR
BANANA

Related

I tried the java language using netbeans 12 with jdk version 8, but it always got an error in the output [duplicate]

I am trying to use Console class to get input from user but a null object is returned when I call System.console(). Do I have to change anything before using System.console?
Console co=System.console();
System.out.println(co);
try{
String s=co.readLine();
}
Using Console to read input (usable only outside of an IDE):
System.out.print("Enter something:");
String input = System.console().readLine();
Another way (works everywhere):
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter String");
String s = br.readLine();
System.out.print("Enter Integer:");
try {
int i = Integer.parseInt(br.readLine());
} catch(NumberFormatException nfe) {
System.err.println("Invalid Format!");
}
}
}
System.console() returns null in an IDE.
So if you really need to use System.console(), read this solution from McDowell.
Scanner in = new Scanner(System.in);
int i = in.nextInt();
String s = in.next();
There are few ways to read input string from your console/keyboard. The following sample code shows how to read a string from the console/keyboard by using Java.
public class ConsoleReadingDemo {
public static void main(String[] args) {
// ====
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter user name : ");
String username = null;
try {
username = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("You entered : " + username);
// ===== In Java 5, Java.util,Scanner is used for this purpose.
Scanner in = new Scanner(System.in);
System.out.print("Please enter user name : ");
username = in.nextLine();
System.out.println("You entered : " + username);
// ====== Java 6
Console console = System.console();
username = console.readLine("Please enter user name : ");
System.out.println("You entered : " + username);
}
}
The last part of code used java.io.Console class. you can not get Console instance from System.console() when running the demo code through Eclipse. Because eclipse runs your application as a background process and not as a top-level process with a system console.
It will depend on your environment. If you're running a Swing UI via javaw for example, then there isn't a console to display. If you're running within an IDE, it will very much depend on the specific IDE's handling of console IO.
From the command line, it should be fine though. Sample:
import java.io.Console;
public class Test {
public static void main(String[] args) throws Exception {
Console console = System.console();
if (console == null) {
System.out.println("Unable to fetch console");
return;
}
String line = console.readLine();
console.printf("I saw this line: %s", line);
}
}
Run this just with java:
> javac Test.java
> java Test
Foo <---- entered by the user
I saw this line: Foo <---- program output
Another option is to use System.in, which you may want to wrap in a BufferedReader to read lines, or use Scanner (again wrapping System.in).
Found some good answer here regarding reading from console, here another way use 'Scanner' to read from console:
import java.util.Scanner;
String data;
Scanner scanInput = new Scanner(System.in);
data= scanInput.nextLine();
scanInput.close();
System.out.println(data);
Try this. hope this will help.
String cls0;
String cls1;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string");
cls0 = in.nextLine();
System.out.println("Enter a string");
cls1 = in.nextLine();
The following takes athspk's answer and makes it into one that loops continually until the user types "exit". I've also written a followup answer where I've taken this code and made it testable.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class LoopingConsoleInputExample {
public static final String EXIT_COMMAND = "exit";
public static void main(final String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter some text, or '" + EXIT_COMMAND + "' to quit");
while (true) {
System.out.print("> ");
String input = br.readLine();
System.out.println(input);
if (input.length() == EXIT_COMMAND.length() && input.toLowerCase().equals(EXIT_COMMAND)) {
System.out.println("Exiting.");
return;
}
System.out.println("...response goes here...");
}
}
}
Example output:
Enter some text, or 'exit' to quit
> one
one
...response goes here...
> two
two
...response goes here...
> three
three
...response goes here...
> exit
exit
Exiting.
I wrote the Text-IO library, which can deal with the problem of System.console() being null when running an application from within an IDE.
It introduces an abstraction layer similar to the one proposed by McDowell.
If System.console() returns null, the library switches to a Swing-based console.
In addition, Text-IO has a series of useful features:
supports reading values with various data types.
allows masking the input when reading sensitive data.
allows selecting a value from a list.
allows specifying constraints on the input values (format patterns, value ranges, length constraints etc.).
Usage example:
TextIO textIO = TextIoFactory.getTextIO();
String user = textIO.newStringInputReader()
.withDefaultValue("admin")
.read("Username");
String password = textIO.newStringInputReader()
.withMinLength(6)
.withInputMasking(true)
.read("Password");
int age = textIO.newIntInputReader()
.withMinVal(13)
.read("Age");
Month month = textIO.newEnumInputReader(Month.class)
.read("What month were you born in?");
textIO.getTextTerminal().println("User " + user + " is " + age + " years old, " +
"was born in " + month + " and has the password " + password + ".");
In this image you can see the above code running in a Swing-based console.
Use System.in
http://www.java-tips.org/java-se-tips/java.util/how-to-read-input-from-console.html

How can I use a scanner to read in integers, more specifically an integer describing a matrix dimension followed by the integers in the matrix?

I can't get my scanner to read in the integer from a text file.
The file looks something like this (a matrix size followed by a matrix)
3
0 1 1
1 1 1
1 0 0
These two methods belong to ReadMatrix
public void openFile() {
try {
scanner = new Scanner(System.in); // create a scanner object
System.out.println("File to read: ");
fileName = scanner.nextLine(); // get name of file
System.out.println("File " + fileName + " is opened.");
br = new BufferedReader(new FileReader(fileName));
} catch (Exception e) {
System.out.println("can't find the funky file");
}
}
public int readInteger() {
sc = new Scanner(System.in);
// while(sc.hasNextInt()){
// sc.nextLine();
anInt = sc.nextInt();
System.out.println("Trying to read integerrrrrr help");
// }
return anInt;
}
Here are 2 classes
public class MainMethodHere {
public static void main(String[] args) {
// TODO Auto-generated method stub
RunMainMethod running = new RunMainMethod();
}
}
public class RunMainMethod {
ReadMatrix a = new ReadMatrix();
public RunMainMethod(){
a.openFile();
a.createFile();
System.out.println("just createdFile"); //<--- this is where the program ends
a.readInteger();
System.out.println("just readInteger");
a.helpMeWrite();
System.out.println("Just write sample ");
a.closeResources();
}
}
Writing to the file works fine, but I can't get the program to read the given text file to start the manipulation.
I tried finding the solutions in a few SO posts: how to read Integer from a text file in Java
Reading numbers from a .txt file into a 2d array and print it on console
How to read integer values from text file
I also tried ReadFile() and WriteFile(), but when I try to track my code via printing into the console, my simple integers shows up as different values. Is that something related to bytes? So I try reverting back to using a scanner, but somehow it's not working. Please let me know if I should clarify something further. I am new to coding and SO.

Having trouble searching a text file for strings

So I'm attempting to simulate a very basic search engine by reading a text file filled with data and then have a user search the file using some keywords, and then whichever "websites" contained in the text file that contain that keyword are returned back to the user. My code so far can read the text file (as far as I know), however no matter the entered keyword, the console almost always states that no results can be found (the text file doesn't contain the keyword(s). Thanks everyone.
Here's the appropriate code:
package myquery;
import java.util.Scanner;
import java.util.*;
import java.io.*;
public class MyQuery{
public static void main(String[] args){
Hashtable<String, ArrayList<String> > hash = new Hashtable<String, ArrayList<String> >();
Scanner input = new Scanner(System.in);
System.out.println("Here is where your .txt file(s) should be located for this program to work properly:");
System.out.println(new java.io.File("").getAbsolutePath());
System.out.println("\nEnter the filename that you want to Search values for. For example \"MyQuery.txt\"");
BufferedReader reader = null;
try{
reader = new BufferedReader(new FileReader(input.nextLine()));
System.out.println("The file was found :) Here are the contents:");
while(reader.ready())
{
String currentline = reader.readLine();
String[] result = currentline.split("\\s");
for(int i = 0; i < result.length; i++)
{
if(!hash.containsKey(result[i]))
{
ArrayList<String> temp = new ArrayList<String>(1);
temp.add(currentline);
hash.put(result[i], temp);
}
else
{
ArrayList<String> temp = (ArrayList<String>)hash.get(result[i]);//
temp.add(currentline);
}
}
}
}
catch(Exception e)
{
System.out.println("Your file was not found unfortunately. Please try again.");
System.exit(1);
}
System.out.println(hash);
do
{
System.out.println("Enter a key to search for the value it is associated with.\n");
System.out.println(hash.get(input.nextLine()));
System.out.println("\nWant to try again? If so, press return and then follow the prompt. Type \"-1\" to quit");
}
while(!input.nextLine().equals("-1"));
try
{
reader.close();
}
catch(Exception e)
{
System.out.println(e);
System.exit(1);
}
}
}
And an example of one line in the text file:
www.Mets.com, "The New York Mets", baseball, team, NY
Here's an example of how the program should respond:
Enter a key to search for the value it is associated with.
Mets
www.Mets.com The New York Mets
Want to try again? If so, press return and then follow the prompt. Type "-1" to quit
But here's what I'm getting instead:
Enter a key to search for the value it is associated with:
Mets
null
Want to try again? If so, press return and then follow the prompt. Type "-1" to quit
ALTHOUGH. If I enter a word that matches any word besides the first/last ones, it works.
For example
Enter a key to search for the value it is associated with:
New
[www.Mets.com, "The New York Mets", baseball, team, NY, www.nytimes.com, "The New York Times", news]
Want to try again? If so, press return and then follow the prompt. Type "-1" to quit

Program does not scan a text file (Java)

I was having trouble getting my program to read from a file "lexicon.txt"
My task was to have the program scan a user input and getting the word count for the program in return. Do you guys know what's going on in my code?
import java.io.*;
import java.util.Scanner;
public class searchFile {
public static void main (String args[]) throws IOException {
Scanner reader = new Scanner(System.in);
System.out.println("Please enter the file name (e.g: nonamefile.txt)");
String objective = reader.nextLine();
if (!(objective.equals("lexicon.txt"))) {
System.out.println("ERROR: Missing File");
}
else {
Scanner reader2 = new Scanner(System.in);
Scanner lexicon = new Scanner(new File("lexicon.txt"));
int wordCount = 0;
System.out.println("What word do you need to look up?");
String objective2 = reader2.nextLine();
while (lexicon.hasNext()) {
String word = lexicon.next();
if (word.equalsIgnoreCase(objective2)){
wordCount++;
}
}
System.out.println("Word count = " + wordCount);
}
} // end main method (String Args[])
} // end class searchFile
I ran your code on my computer. It is to help you. may be you are not doing same.
Please enter the file name (e.g: nonamefile.txt)
lexicon.txt
What word do you need to look up?
three
Word count = 3
The text I used in lexicon.txt was that :
one
two two
three three three
And it is working fine.
Remember, just copy paste is not like what you think it. there could be any character in clipboard when you copy that you cannot see, and pasting it also pastes these code too in your text file.
Scanner.next() looks for the next string delimited by word boundries.
Suppose there is a text that you copy pasted :
which is not visible in notepad :
So when you will search for "Hello", it will not be there.
You will have to search for instead, but you cannot write this easily.

Reading a string with new lines from console java

I want to read this string (from console not file) for example:
one two three
four five six
seven eight nine
So I want to read it per line and put every line in an array.
How can I read it? Because if I use scanner, I can only read one line or one word (nextline or next).
what I mean is to read for example : one two trhee \n four five six \n seven eight nine...
You should do by yourself!
There is a similer example:
public class ReadString {
public static void main (String[] args) {
// prompt the user to enter their name
System.out.print("Enter your name: ");
// open up standard input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String userName = null;
// read the username from the command-line; need to use try/catch with the
// readLine() method
try {
userName = br.readLine();
} catch (IOException ioe) {
System.out.println("IO error trying to read your name!");
System.exit(1);
}
System.out.println("Thanks for the name, " + userName);
}
} // end of ReadString class
To answer the question as clarified in the comment on the first answer:
You must call Scanner's nextLine() method once for each line you wish to read. This can be accomplished with a loop. The problem you will inevitably encounter is "How do I know big my result array should be?" The answer is that you cannot know if you do not specify it in the input itself. You can modify your programs input specification to require the number of lines to read like so:
3
One Two Three
Four Five
Six Seven Eight
And then you can read the input with this:
Scanner s = new Scanner(System.in);
int numberOfLinesToRead = new Integer(s.nextLine());
String[] result = new String[numberOfLinesToRead];
String line = "";
for(int i = 0; i < numberOfLinesToRead; i++) { // this loop will be run 3 times, as specified in the first line of input
result[i] = s.nextLine(); // each line of the input will be placed into the array.
}
Alternatively you can use a more advanced data structure called an ArrayList. An ArrayList does not have a set length when you create it; you can simply add information to it as needed, making it perfect for reading input when you don't know how much input there is to read. For example, if we used your original example input of:
one two trhee
four five six
seven eight nine
You can read the input with the following code:
Scanner s = new Scanner(System.in);
ArrayList<String> result = new ArrayList<String>();
String line = "";
while((line = s.nextLine()) != null) {
result.add(line);
}
So, rather than creating an array of a fixed length, we can simply .add() each line to the ArrayList as we encounter it in the input. I recommend you read more about ArrayLists before attempting to use them.
tl;dr: You call next() or nextLine() for each line you want to read using a loop.
More information on loops: Java Loops
Look at this code:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class SearchInputText {
public static void main(String[] args) {
SearchInputText sit = new SearchInputText();
try {
System.out.println("test");
sit.searchFromRecord("input.txt");
System.out.println("test2");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void searchFromRecord(String recordName) throws IOException {
File file = new File(recordName);
Scanner scanner = new Scanner(file);
StringBuilder textFromFile = new StringBuilder();
while (scanner.hasNext()) {
textFromFile.append(scanner.next());
}
scanner.close();
// read input from console, compare the strings and print the result
String word = "";
Scanner scanner2 = new Scanner(System.in);
while (((word = scanner2.nextLine()) != null)
&& !word.equalsIgnoreCase("quit")) {
if (textFromFile.toString().contains(word)) {
System.out.println("The word is on the text file");
} else {
System.out.println("The word " + word
+ " is not on the text file");
}
}
scanner2.close();
}
}

Categories