java scanner to detect 3 words on line - java

I am trying to write a little program that will use scanner to check if there is a next line (in awhile loop) and then maybe another one to check that the words on the line are tab appart and there are 3 strings (the use constructor to create a object) so the three strings would be Product Name Manufacturer Brcode
EG: Tyre17x60 Goodyear 458765464
and so and so
I am bit stuck with this so any help would be grateful

You can try this:
public static void main (String[] args) throws java.lang.Exception
{
String str = "Tyre17x60 Goodyear 458765464";
InputStream is = new ByteArrayInputStream(str.getBytes());
Scanner sc = new Scanner(is);
sc.useDelimiter("\n");
while (sc.hasNext())
{
String[] tmp = sc.next().split("\t");
if (tmp.length == 3)
System.out.println("Text contains 3 parts separated with tabs");
else
System.out.println("Text is not well formated");
// save data
//productName = tmp[0];
//manufacturer = tmp[1];
//brcode = tmp[2];
}
}

Assuming you are reading from a file, you can use the following code:
Scanner s = new Scanner(new File("file.txt"));
while(s.hasNext())
{
String productName = s.next();
String Manufacturer = s.next();
String Brcode = s.next();
}

Scanner scan = new Scanner("file.txt");
while(scan.hasNext()){
scan.nextLine();
System.out.println("Product : " + scan.next());
System.out.println("Name : " + scan.next());
System.out.println("Code : " + scan.nextLong());
}
Try something like this....

Related

Java scanner test for empty line

I'm using Scanner to read 3 lines of input, the first two are strings and the last one is int.
I'm having an issue when the first line is empty and I don't know how to get around it. I have to do this:
String operation = sc.nextLine();
String line = sc.nextLine();
int index = sc.nextInt();
encrypt(operation,line,index);
But when the first line is empty I get an error message.
I tried the following to force a loop until I get a non empty next line but it does not work either:
while(sc.nextLine().isEmpty){
operation = sc.nextLine();}
Anybody has a hint please ?
A loop should work, though you must actually call the isEmpty method and scan only once per iteration
String operation = "";
do {
operation = sc.nextLine();
} while(operation.isEmpty());
You could also use sc.hasNextLine() to check if anything is there
Try this:
Scanner scanner = new Scanner(reader);
String firstNotEmptyLine = "";
while (scanner.hasNext() && firstNotEmptyLine.equals("")) {
firstNotEmptyLine = scanner.nextLine();
}
if (!scanner.hasNext()) {
System.err.println("This whole file is filled with empty lines! (or the file is just empty)");
return;
}
System.out.println(firstNotEmptyLine);
Then you can read the other two lines after this firstNotEmptyLine.
Please try this.
Scanner sc = new Scanner(System.in);
String operation = null;
String line = null;
int index = 0;
while(sc.hasNext()) {
String nextLine = sc.nextLine().trim();
if(!nextLine.isEmpty()) {
operation = nextLine;
break;
}
}
while(sc.hasNext()) {
String nextLine = sc.nextLine().trim();
if(!nextLine.isEmpty()) {
line = nextLine;
break;
}
}
while(sc.hasNext()) {
String nextLine = sc.nextLine().trim();
if(!nextLine.isEmpty()) {
index = Integer.parseInt(nextLine);
break;
}
}
System.out.println(operation + " " + line + " " + index);
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
String operation = sc.nextLine();
String line = sc.nextLine();
int index = sc.nextInt();
test(operation,line,index);
}
public static void encrypt(String a,String b,int c){
System.out.println("first :"+a+" Second :"+b+" Third :"+c);
}
I don't see any error here. It compiles well.

compare two files and print differences in Java

I tried to compare two files and print out the differences between them. However, my code only print the last sentence which is where the second difference in each file.
/*
-------------------------------
data1:
This file has a great deal of
text in it which needs to
be processed.
-------------------------------
data2:
This file has a grate deal of
text in it which needs to
bee procesed.
-------------------------------
*/
import java.io.*;
import java.util.*;
public class CompareTwoFiles {
public static void main(String[] args) throws FileNotFoundException {
String first = "", second = "";
String firstName = "", secondName = "";
Scanner input = new Scanner(System.in);
System.out.print("Enter a first file name: ");
firstName = input.nextLine();
System.out.print("Enter a second file name: ");
secondName = input.nextLine();
Scanner input1 = new Scanner(new File(firstName));//read first file
while (input1.hasNextLine()) {
first = input1.nextLine();
}
Scanner input2 = new Scanner(new File(secondName));//read second file
while (input2.hasNextLine()) {
second = input2.nextLine();
}
if (!first.equals(second)) {
System.out.println("Differences found: " + "\n" + first + '\n' + second);
}
}
}
/*
output:
Enter a first file name: data1.txt
Enter a second file name: data2.txt
Differences found:
be processed.
bee procesed.
*/
Your code should be
Scanner input1 = new Scanner(new File(firstName));//read first file
Scanner input2 = new Scanner(new File(secondName));//read second file
while(input1.hasNextLine() && input2.hasNextLine()){
first = input1.nextLine();
second = input2.nextLine();
if(!first.equals(second)){
System.out.println("Differences found: "+"\n"+first+'\n'+second);
}
}
// optionally handle any remaining lines if the line count differs
Previously you only compared one time, the very last line. But you need to compare after each line you read.

java find a specific line in a file based on the first word

I have a file that I am importing and what I want do is ask for the user's input and use that as the basis for finding the right line to examine. I have it set up like this:
public class ReadLines {
public static void main(String[] args) throws FileNotFoundException
{
File fileNames = new File("file.txt");
Scanner scnr = new Scanner(fileNames);
Scanner in = new Scanner(System.in);
int count = 0;
int lineNumber = 1;
System.out.print("Please enter a name to look up: ");
String newName = in.next();
while(scnr.hasNextLine()){
if(scnr.equals(newName))
{
String line = scnr.nextLine();
System.out.print(line);
}
}
}
Right now, I am just trying to get it to print out to see that I have captured it, but that's not working. Does anyone have any ideas? Also, if it matters, I can't use try and catch or arrays.
Thanks a lot!
You need to cache the line in a local variable so you can print it out later. Something like this should do the trick:
while(scnr.hasNextLine()){
String temp = scnr.nextLine(); //Cache variable
if (temp.startsWith(newName)){ //Check if it matches
System.out.println(temp); //Print if match
}
}
Hope this helps!
I'd do something in the lines of:
Scanner in = new Scanner(System.in);
System.out.print("Please enter a name to look up: ");
String name = in.next();
List<String> lines = Files.readAllLineS(new File("file.txt").toPath(), StandardCharsets.UTF_8);
Optional<String> firstResult = lines.stream().filter(s -> s.startsWith(name)).findFirst();
if (firstResult.isPresent) {
System.out.print("Line: " + firstResult.get());
} else {
System.out.print("Nothing found");
}

Line/Token based processing (java)

I'm writing a program to read data from files with various sports statistics. Each line has information about a particular game, in say, basketball. If a particular line contains an "#" symbol, it means that one of the teams is playing at home. I'm trying to count the lines that contain an "#" and output that to the user as the Number of Games in which either team played at home. The first file has that 9 games were played at home for some team, but my output keeps printing out 0 rather than 9. How can I fix this?
Here's the relevant code:
public static void numGamesWithHomeTeam(String fileName) throws IOException{
File statsFile = new File(fileName);
Scanner input1 = new Scanner(statsFile);
String line = input1.nextLine();
Scanner lineScan = new Scanner(line);
int count = 0;
while(input1.hasNextLine()){
if(line.contains("#")){
count++;
input1.nextLine();
} else{
input1.nextLine();
}
}
System.out.println("Number of games with a home team: " + count);
}
Your line variable always has the first line's value. You should set line in the loop, something like that.
while(input1.hasNextLine()){
if(line.contains("#")){
count++;
line = input1.nextLine();
} else{
line = input1.nextLine();
}
Edit: On the second look your code has other problem: the last line is never checked. You should not initialize line (set to null) and do the check after nextLine():
public static void numGamesWithHomeTeam(String fileName) throws IOException{
File statsFile = new File(fileName);
Scanner input1 = new Scanner(statsFile);
String line = null;
Scanner lineScan = new Scanner(line);
int count = 0;
while(input1.hasNextLine()){
line = input1.nextLine();
if(line.contains("#")){
count++;
}
}
System.out.println("Number of games with a home team: " + count);}

Java - Storing Several string inputs using a loop and input.nextline();

I'm trying to get a set of string statements (which can include spaces) into a string array. The number of statements will be decided by the input of the user.
So I thought of looping the input.nextline(); function.
But I think as soon as enter is hit it is taken as \n to all the loops..
Is there any better way to do this?
Scanner input = new Scanner(System.in);
System.out.println("How many Inputs??");
numOfInputs = input.nextInt();
String[] dataStore = new String[numOfInputs];
System.out.println("Input Strings");
for(i=0;i<numOfInputs;i++){
System.out.print("Input "+(i+1)+ " = ");
dataStore[i] = input.next();
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many Inputs??");
int numOfInputs = input.nextInt();
String[] dataStore = new String[numOfInputs];
System.out.println("Input Strings");
for (int i = 0; i < numOfInputs; i++) {
dataStore[i] = input.next();
System.out.println("Input " + (i + 1) + " = " + dataStore[i]);
}
}
Try this . I corrected the mistakes.
Add this to the bottom after the for loop, your code is working fine:
for(String str : dataStore) {
System.out.println(str);
}

Categories

Resources