Using Scanner to read in a text file - java

I have a text file with the following line define : Hi 0x01. I'm trying to read in the word Hi and store it in its own variables and 0x01 in its own variable.The problem I'm having is that i seem to be able to read in Hi, but i cant read in0x01`.Here is my code
File comms =new File("src/Resources/com.txt");
try (Scanner scan = new Scanner(comms)) {
while (scan.hasNext()) {
String line = scan.nextLine();
Scanner sc = new Scanner(line);
sc.useDelimiter("\\s+");
try {
String comm1 = sc.next();
// System.out.println(comm1);
int value =sc.nextInt();
System.out.println(value);
sc.close();
} catch (Exception ef){
}

I honestly have no idea what you're trying to do here. You'd better scan it once:
File comms = new File("src/Resources/com.txt");
try(Scanner scan = new Scanner(comms)) {
while(scan.hasNext()) {
String line = scan.nextLine();
String[] words = line.split(" ");
System.out.println(words[0]); // "Hi"
System.out.println(words[1]); // "0x01"
}
}
catch(Exception e) {
}
Now, having these in separate strings you can do anything in the world with it like converting words[1] to int.

Related

Scanning input into char array Java

I was trying to store input as
5
3DRP 3QEW
8AQW 9ADA
I want to read that input in as a copy paste and put it. I've tried this:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String userNumber;
userNumber = scan.nextLine();
String[] tokens = userNumber.split("[ ]");
System.out.println(tokens[1]);
for(int i = 0; i < tokens.length;i++) {
System.out.println(tokens[i]);
}
scan.close();
}
My goal is to basically read that input in as a copy paste into the IDE or through a file a .txt and then store every single character besides whitespaces into a char array that is 1d or 2d.
From what I understand, you want to read 3 lines from the console, remove all the white spaces from that text and store it as a char array.
If that is the case, here is how you could do that:
int numberOfLinesToRead = 3;
try(Scanner sc = new Scanner(System.in)){
StringBuilder buff = new StringBuilder();
while(numberOfLinesToRead-- > 0){
String line = sc.nextLine();
String noSpaces = line.replaceAll("\\s", "");
buff.append(noSpaces);
}
char[] characters = buff.toString().toCharArray();
System.out.println(Arrays.toString(characters));
}catch (Exception e) {
e.printStackTrace();
}

Writing a program in Java to read in multiple strings from user and compare to text file

I am attempting to write a program that will take user input ( a long message of characters), store the message and search a text file to see if those words occur in the text file. The problem I am having is that I am only ever able to read in the first string of the message and compare it to the text file. For instance if I type in "learning"; a word in the text file, I will get a result showing that is is found in the file. However if I type "learning is" It will still only return learning as a word found in the file even though "is" is also a word in the text file. My program seems to not be able to read past the blank space. So I suppose my questions is, how do I augment my program to do this and read every word in the file? Would it also be possible for my program to read every word, with or without spaces, in the original message taken from the user, and compare that to the text file?
Thank you
import java.io.*;
import java.util.Scanner;
public class Affine_English2
{
public static void main(String[] args) throws IOException
{
String message = "";
String name = "";
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
System.out.println("Please enter in a message: ");
message = scan.next();
Scanner file = new Scanner(new File("example.txt"));
while(file.hasNextLine())
{
String line = file.nextLine();
for(int i = 0; i < message.length(); i++)
{
if(line.indexOf(message) != -1)
{
System.out.println(message + " is an English word ");
break;
}
}
}
}
}
I recommend you first process the file and build a set of legal English words:
public static void main(String[] args) throws IOException {
Set<String> legalEnglishWords = new HashSet<String>();
Scanner file = new Scanner(new File("example.txt"));
while (file.hasNextLine()) {
String line = file.nextLine();
for (String word : line.split(" ")) {
legalEnglishWords.add(word);
}
}
file.close();
Next, get input from the user:
Scanner input = new Scanner(System.in);
System.out.println("Please enter in a message: ");
String message = input.nextLine();
input.close();
Finally, split the user's input to tokens and check each one if it is a legal word:
for (String userToken : message.split(" ")) {
if (legalEnglishWords.contains(userToken)) {
System.out.println(userToken + " is an English word ");
}
}
}
}
You may try with this. With this solution you can find each word entered by the user in your example.txt file:
public static void main(String[] args) throws IOException
{
String message = "";
String name = "";
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
System.out.println("Please enter in a message: ");
message = scan.nextLine();
Scanner file = new Scanner(new File("example.txt"));
while (file.hasNextLine())
{
String line = file.nextLine();
for (String word : message.split(" "))
{
if (line.contains(word))
{
System.out.println(word + " is an English word ");
}
}
}
}
As Mark pointed out in the comment, change
scan.next();
To:
scan.nextLine();
should work, i tried and works for me.
If you can use Java 8 and Streams API
public static void main(String[] args) throws Exception{ // You need to handle this exception
String message = "";
Scanner input = new Scanner(System.in);
System.out.println("Please enter in a message: ");
message = input.nextLine();
List<String> messageParts = Arrays.stream(message.split(" ")).collect(Collectors.toList());
BufferedReader reader = new BufferedReader(new FileReader("example.txt"));
reader.lines()
.filter( line -> !messageParts.contains(line))
.forEach(System.out::println);
}
You have many solution, but when it comes to find matches I suggest you to take a look to the Pattern and Matcher and use Regular Expression
I haven't fully understood your question, but you could do add something like this (I did not tested the code but the idea should work fine):
public static void main(String[] args) throws IOException{
String message = "";
String name = "";
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
System.out.println("Please enter in a message: ");
message = scan.next();
Scanner file = new Scanner(new File("example.txt"));
String pattern = "";
for(String word : input.split(" ")){
pattern += "(\\b" + word + "\\b)";
}
Pattern r = Pattern.compile(pattern);
while(file.hasNextLine())
{
String line = file.nextLine();
Matcher m = r.matcher(line);
if(m.matches()) {
System.out.println("Word found in: " + line);
}
}
}

Skipping whitespace on new line?

I can't seem to get this correct. Basically if the line is blank inside the text file it should skip the line instead of numbering it.
Ex: If the file contains, Apples,Oranges,Pineapples
it should produce
Apples
Oranges
Pineapples
or
1. Apples
(blank)
Oranges
Pineapples
try {
Scanner reader = new Scanner(System.in);
System.out.print("Enter file name with extension: ");
File file = new File(reader.nextLine());
reader = new Scanner(file);
int counter = 1;
while (reader.hasNextLine())
{
if (reader.equals(" ")){
System.out.println();
}else{
String line = reader.nextLine();
System.out.printf("%2d.", counter++); // Use printf to format
System.out.println(line);
}
}
reader.close();
} catch (Exception ex){
ex.printStackTrace();
}
}
}
Space or " " is actually totally different to an empty line...
so the reason why is not working is the condition
if (reader.equals(" ")){.....
use instead the String.isEmpty() method, since this is what you need...
or try this:
...
reader = new Scanner(file);
int counter = 1;
while (reader.hasNextLine()) {
final String line = reader.nextLine();
if (line.isEmpty()) {
System.out.println("This is an empty line");
} else {
System.out.printf("%2d.", counter++); // Use printf to format
System.out.println(line);
}
}
reader.close();
...

Swing Java GUI reading a text file with scanner

I am trying to build a GUI app, which would read a text file on the press of a button
and then save contents of this file to a string. My current code, I basically tried to adapt my console code for the gui, but it doesnt seem to work. Here is my button code:
private void convertButtonActionPerformed(java.awt.event.ActionEvent evt) {
Scanner user_input = new Scanner(tempTextField.getText());
String seq1 = user_input.next();
Scanner scanner = new Scanner(new File(seq1));
scanner.nextLine();
String content = scanner.useDelimiter("\\Z").next();
int N = content.length();
textarea.append("Length of the input string is: "+N);
}
textarea = JtextArea
tempTextField = JTextField
Thank you.
edit: I'm using netbeans IDE
You must handle the exception from Scanner scanner = new Scanner(new File(seq1)):
private void convertButtonActionPerformed(java.awt.event.ActionEvent evt)
{
Scanner user_input = null;
Scanner scanner = null;
try
{
user_input = new Scanner(tempTextField.getText());
String seq1 = user_input.next();
scanner = new Scanner(new File(seq1));
scanner.nextLine();
String content = scanner.useDelimiter("\\Z").next();
int N = content.length();
textarea.append("Length of the input string is: "+N);
}catch(FileNotFoundException e)
{
e.printStackTrace();
}finally
{
//always close scanner
if(user_input != null)
user_input.close();
if(scanner != null)
scanner.close();
}
}
These are known as 'Checked Exceptions'. Here, the compiler would force you to handle such code in try/catch block, i.e to Report the Exception, only then you can move forward for execution.

I have to make a loop taking a users input until "done" is entered

I'm trying to make an ArrayList that takes in multiple names that the user enters, until the word done is inserted but I'm not really sure how. How to achieve that?
ArrayList<String> list = new ArrayList<String>();
String input = null;
while (!"done".equals(input)) {
// prompt the user to enter an input
System.out.print("Enter input: ");
// open up standard input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// read the input from the command-line; need to use try/catch with the
// readLine() method
try {
input = br.readLine();
} catch (IOException ioe) {
System.out.println("IO error trying to read input!");
System.exit(1);
}
if (!"done".equals(input) && !"".equals(input))
list.add(input);
}
System.out.println("list = " + list);
I would probably do it like this -
public static void main(String[] args) {
System.out.println("Please enter names seperated by newline, or done to stop");
Scanner scanner = new Scanner(System.in); // Use a Scanner.
List<String> al = new ArrayList<String>(); // The list of names (String(s)).
String word; // The current line.
while (scanner.hasNextLine()) { // make sure there is a line.
word = scanner.nextLine(); // get the line.
if (word != null) { // make sure it isn't null.
word = word.trim(); // trim it.
if (word.equalsIgnoreCase("done")) { // check for done.
break; // End on "done".
}
al.add(word); // Add the line to the list.
} else {
break; // End on null.
}
}
System.out.println("The list contains - "); // Print the list.
for (String str : al) { // line
System.out.println(str); // by line.
}
}
String[] inputArray = new String[0];
do{
String input=getinput();//replace with custom input code
newInputArray=new String[inputArray.length+1];
for(int i=0; i<inputArray.length; i++){
newInputArray[i]=inputArray[i];
}
newInputArray[inputArray.length]=input
intputArray=newInputArray;
}while(!input.equals("done"));
untested code, take it with a grain of salt.
ArrayList<String> names = new ArrayList<String>();
String userInput;
Scanner scanner = new Scanner(System.in);
while (true) {
userInput = scanner.next();
if (userInput.equals("done")) {
break;
} else {
names.add(userInput);
}
}
scanner.close();

Categories