When I try to compile my code I get the message
Main.java:31: error: not a statement
String bed = f.split(" ")
and also
error: ';' expected
String bed = f.split(" ");
I don't understand what's going on. I need to assign part of a file to a string.
Here's the code :
import java.util.Scanner;
import java.io.*;
public class Main{
public static void main(String[] args){
if ( args[0] == null){
System.out.println("File not Found");
return;
}
try {
File driver = new File (args[0]);
Scanner j = new Scanner( driver );
int i = 0;
while( j.hasNextLine()) {
String f = j.nextLine();
if (f.isEmpty() || f.startsWith("/")){ //If the String f is empty or has / it will continue reading the nextline after the / or space
continue;
if (f.startsWith("d")) {
String d = f.split(" ");
}
if (f.startsWith("b")) {
String b = f.split(" ");
}
if (f.startsWith("bed"))
String bed = f.split(" ");
}
System.out.println(f);
}
}
catch(FileNotFoundException e) {
System.out.println(e.getMessage());
}
catch (Exception ex) {
System.out.println(ex.getMessage);
}
}
}
.split() method returns an array so you should store it in an array, not in a string. Your code should be string b[]=f.split(" ") rather than storing it in string b
The split method returns splits the string based on the regex and returns an String array.
What you have here is String d = f.split(" ");, here you are trying to assign a string array to a string, and that is wrong.
It should instead say String[] d = f.split(" ");
I had this error.
I found a solution like below.
Error code
String a = "I goto the school";
String [] b = a.split("\\\s"); // error not a statement
Run code
try
{
String a = "I goto the school";
String [] b = a.split("\\\s");
}
catch(exception e)
{
}
Related
File Roster: roster.txt
Reagan rebradshaw835
Ryley rbarber894
Peyton pstott885
Tyrese tmayo945
Caius ccharlton329
The program has to do with exception handling. Problem I am trying to overcome at the moment is being able to get the proper output. I don't know if there is a specific way to find the line that contains the name, and return everything in the line except the name.
so that we are able to return the username assigned.
For example, first line shows:
Reagan rebradshaw835
Method returns just rebradshaw835
Here is the code: (updated code)
vhthanh really helped me to understand how to read from a file!
I decided to edit the code using replace string commands. Without vhthanhI probably wouldn't have learned how to interact with the file.
package chapter11;
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.IOException;
public class LabProgram {
public static String findID(String studentName, Scanner infoScnr) throws Exception {
while (infoScnr.hasNextLine()) {
String line = infoScnr.nextLine();
//String[] values = line.split(" ", 2);
if (line.contains(studentName)) {
line = line.replace(studentName + " ", "");
return line;
}
}
throw new Exception ("Student ID not found for " + studentName);
}
public static String findName(String studentID, Scanner infoScnr) throws Exception {
while (infoScnr.hasNextLine()) {
String line = infoScnr.nextLine();
//String[] values = line.split(" ", 2);
if (line.contains(studentID)) {
line = line.replace(studentID + " ", "");
return line;
}
}
throw new Exception ("Student name not found for " + studentID);
}
public static void main(String[] args) throws IOException {
Scanner scnr = new Scanner(System.in);
String studentName;
String studentID;
String studentInfoFileName;
FileInputStream studentInfoStream = null;
Scanner studentInfoScanner = null;
// Read the text file name from user
studentInfoFileName = scnr.next();
// Open the text file
studentInfoStream = new FileInputStream(studentInfoFileName);
studentInfoScanner = new Scanner(studentInfoStream);
// Read search option from user. 0: findID(), 1: findName()
int userChoice = scnr.nextInt();
// FIXME: findID() and findName() may throw an Exception.
// Insert a try/catch statement to catch the exception and output the exception message.
try {
if (userChoice == 0) {
studentName = scnr.next();
studentID = findID(studentName, studentInfoScanner);
System.out.println(studentID);
}
else {
studentID = scnr.next();
studentName = findName(studentID, studentInfoScanner);
System.out.println(studentName);
}
studentInfoStream.close();
}
catch (Exception exp) {
System.out.println(exp.getMessage());
}
}
}
You need to read the every single line from the Scanner and split() the string into an array of 2 values and then compare it.
Try this code:
public static String findID(String studentName, Scanner infoScnr) throws Exception {
while (infoScnr.hasNextLine()) {
String line = infoScnr.nextLine();
String[] values = line.split(" ", 2);
if (studentName != null && studentName.equals(values[0])) {
return values[1];
}
}
throw new Exception ("Student name not found for " + studentName);
}
public static String findName(String studentID, Scanner infoScnr) throws Exception {
while (infoScnr.hasNextLine()) {
String line = infoScnr.nextLine();
String[] values = line.split(" ", 2);
if (studentID != null && values.length > 1 && studentID.equals(values[1])) {
return values[0];
}
}
throw new Exception ("Student id not found for " + studentID);
}
.split (" ")
for spacing
.split ("/n")
for new line (nextLine)
I am getting an error in my code which I cannot seem to wrap my head around. In my code I am parsing a data file and setting the values to my local variables that will later be turned into an object and added to the productList. But Somewhere in my while loop, the program stops running and
1 is printed to standard out and it says build successful (im using netbeans)
I tried catching the exception and printing it out using e.getmessage() but nothing will print and I know for a fact the error is in the try block because I used print statements to find out when the error occurs. This method is also inside a menu function that is not supposed to end the method input finishes.
public void input(ArrayList productList) {
String type = "";
String name = "";
String authors = "";
String publisher = "";
String maker = "";
String productID = "";
String priceS = "";
String yearS = "";
String filepath = "/home/alex/Desktop/CS/products.txt";
try{
File f = new File(filepath);
Scanner sc = new Scanner(f);
while(sc.hasNextLine()){
String theData = sc.nextLine();
if(theData.contains("type")){
type = theData;
} else if(theData.contains("productID")){
productID = theData;
} else if(theData.contains("name")){
name = theData;
} else if(theData.contains("price")){
priceS = theData;
} else if(theData.contains("year")){
yearS = theData;
} else if(theData.contains("maker")){
maker = theData;
} else if(theData.contains("authors")){
authors = theData;
} else if(theData.contains("publisher")){
publisher = theData;
}
}
} catch(Exception e){
System.out.println("ERROR: " + e.getMessage());
}
}
I have a simple problem.
I wrote a method in java to get the contents of text file.
public static String[] viewSuppliers()
{
Scanner x = null;
try{
x = new Scanner(new File("C:\\Users\\فاطمة\\Downloads\\suppliers.txt"));
while(x.hasNext())
{
String a = x.next();
String b = x.next();
String c = x.next();
String d = x.next();
String array[] = {a,b,c,d};
return array;
}
x.close();
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
I have called this method in main program but it only returns one line of the file. The contents of my text file are like this:
PEPSI John London 214222
COLA Sarah France 478800
Here is my main program:
String array3[] = {"Supplier Company: ", "Supplier Name: ", "Supplier Address: ",
"Supplier Phone Number: "};
String array4[] = i.viewSuppliers(); // object of class
if(i.viewSuppliers() == null)
System.out.println("No current suppliers.");
else
{
System.out.println("Current Suppliers: ");
for(int u = 0; u < array3.length; u++)
{
System.out.printf(array3[u]);
System.out.println(array4[u]);
}
}
When i run the main program and call the method it is only return the first line and i want to return all the file.
Instead of returning an array of 4 strings,
it seems what you really want is to return a list of array of 4 strings:
public static List<String[]> viewSuppliers()
{
List<String[]> lines = new ArrayList<>();
Scanner x = null;
try{
x = new Scanner(new File("C:\\Users\\فاطمة\\Downloads\\suppliers.txt"));
while(x.hasNext())
{
String a = x.next();
String b = x.next();
String c = x.next();
String d = x.next();
String array[] = {a,b,c,d};
lines.add(array);
}
x.close();
}
catch(Exception e)
{
e.printStackTrace();
}
return lines;
}
Then, iterate over the results:
List<String[]> list = i.viewSuppliers(); // object of class
if (list.isEmpty())
System.out.println("No current suppliers.");
else
{
System.out.println("Current Suppliers: ");
for (String[] supplier : list) {
for(int u = 0; u < array3.length; u++)
{
System.out.printf(array3[u]);
System.out.println(supplier[u]);
}
}
}
Try take the return out of the while loop, otherwise after the first iteration it returns.
You have the output on a loop based on the length of array3, but not array4, so it will always only print the first supplier because of the length of array3.
System.out.println("Current Suppliers: ");
for(int u = 0; u < array3.length; u++)
{
System.out.printf(array3[u]);
System.out.println(array4[u]);
}
Perhaps adding the System.out.println(array4) to a loop based on its length below the first loop.
I have a text file:
John Smith 2009-11-04
Jenny Doe 2009-12-29
Alice Jones 2009-01-03
Bob Candice 2009-01-04
Carol Heart 2009-01-07
Carlos Diaz 2009-01-10
Charlie Brown 2009-01-14
I'm trying to remove the dashes and store them as separate types: first, last, year,month,day and then add it to a sortedset/hashmap. But for some reason. It's not working right.
Here is my code:
public class Test {
File file;
private Scanner sc;
//HashMap<Name, Date> hashmap = new HashMap<>();
/**
* #param filename
*/
public Test(String filename) {
file = new File(filename);
}
public void openFile(String filename) {
// open the file for scanning
System.out.println("Test file " + filename + "\n");
try {
sc = new Scanner(new File("birthdays.dat"));
}
catch(Exception e) {
System.out.println("Birthdays: Unable to open data file");
}
}
public void readFile() {
System.out.println("Name Birthday");
System.out.println("---- --------");
System.out.println("---- --------");
while (sc.hasNext()) {
String line = sc.nextLine();
String[] split = line.split("[ ]?-[ ]?");
String first = split[0];
String last = split[1];
//int year = Integer.parseInt(split[2]);
//int month = Integer.parseInt(split[3]);
//int day = Integer.parseInt(split[4]);
Resource name = new Name(first, last);
System.out.println(first + " " + last + " " + split[2] );
//hashmap.add(name);
}
}
public void closeFile() {
sc.close();
}
public static void main(String[] args) throws FileNotFoundException,
ArrayIndexOutOfBoundsException {
try {
Scanner sc = new Scanner( new File(args[0]) );
for( int i = 0; i < args.length; i++ ) {
//System.out.println( args[i] );
if( args.length == 0 ) {
}
else if( args.length >= 1 ) {
}
// System.out.printf( "Name %-20s Birthday", name.toString(), date.toString() );
}
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Usage: Birthdays dataFile");
// Terminate the program here somehow, or see below.
System.exit(-1);
} catch (FileNotFoundException e) {
System.err.println("Birthdays: Unable to open data file");
// Terminate the program here somehow, or see below.
System.exit(-1);
}
Test r = new Test(args[0]);
r.openFile(args[0]);
r.readFile();
r.closeFile();
}
}
Your splitting on dashes but your is program is build around a split using spaces.
Try just splitting on spaces
String[] split = line.split("\\s");
So "John Smith 2009-11-04".split("[ ]?-[ ]?"); results in ["John Smith 2009", "11", "04"] When what you want is for it to split on spaces ["John", "Smith", "2009-11-04"]
I would do this differently, first create a domain object:
public class Person {
private String firstName;
private String lastName;
private LocalDate date;
//getters & setters
//equals & hashCode
//toString
}
Now create a method that parses a single String of the format you have to a Person:
//instance variable
private final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
public Person parsePerson(final String input) {
final String[] data = input.split("\\s+");
final Person person = new Person();
person.setFirstName(data[0]);
person.setLastName(data[1]);
person.setDate(LocalDate.parse(data[2], dateTimeFormatter));
return person;
}
Note that the DateTimeFormatter is an instance variable, this is for speed. You should also set the ZoneInfo on the formatter if you need to parse dates not in your current locale.
Now, you can read your file into a List<Person> very easily:
public List<Person> readFromFile(final Path path) throws IOException {
try (final Stream<String> lines = Files.lines(path)) {
return lines
.map(this::parsePerson)
.collect(toList());
}
}
And now that you have a List<Person>, you can sort or process them however you want.
You can even do this while creating the List:
public List<Person> readFromFile(final Path path) throws IOException {
try (final Stream<String> lines = Files.lines(path)) {
return lines
.map(this::parsePerson)
.sorted(comparing(Person::getLastName).thenComparing(Person::getFirstName))
.collect(toList());
}
}
Or have your Person implements Comparable<Person> and simply use natural order.
TL;DR: Use Objects for your objects and life becomes much simpler.
I would use a regex:
private static Pattern LINE_PATTERN
= Pattern.compile("(.+) (.+) ([0-9]{4})-([0-9]{2})-([0-9]{2})");
...
while (sc.hasNext()) {
String line = sc.nextLine();
Matcher matcher = LINE_PATTERN.matcher(line);
if (!matcher.matches()) {
// malformed line
} else {
String first = matcher.group(1);
String last = matcher.group(2);
int year = Integer.parseInt(matcher.group(3));
int month = Integer.parseInt(matcher.group(4));
int day = Integer.parseInt(matcher.group(5));
// do something with it
}
}
You are splitting on spaces and a hyphen. This pattern does not exist.
String[] split = line.split("[ ]?");
String first = split[0];
String last = split[1];
line = split[2];
//now split the date
String[] splitz = line.split("-");
or something like this might work:
String delims = "[ -]+";
String[] tokens = line.split(delims);
If i understood your question right then Here is answer. Check it out.
List<String> listGet = new ArrayList<String>();
String getVal = "John Smith 2009-11-04";
String[] splited = getVal.split("[\\-:\\s]");
for(int j=0;j<splited.length;j++)
{
listGet.add(splited[j]);
}
System.out.println("first name :"+listGet.get(0));
System.out.println("Last name :"+listGet.get(1));
System.out.println("year is :"+listGet.get(2));
System.out.println("month is :"+listGet.get(3));
System.out.println("day is :"+listGet.get(4));
OP :
first name :John
Last name :Smith
year is :2009
month is :11
day is :04
this method runs an exception and i didn't find why.
private void loadTrace () {
BufferedReader reader = new BufferedReader(
new StringReader(logTextArea.getText()));
String str;
try {
while(reader != null)
{
str =reader.readLine();
String [] splitted = str.split("\\|");
String b = splitted[1].trim();
String c = splitted[2].trim();
String d = splitted[3].trim();
String Chemin;
String Type = "action" ;
String Description;
if (d!=null) {
Description=d;
}
else Description ="Afficher onglet";
if (c!= null) {
Chemin= b+"."+c;
}
else Chemin =b;
String trace =Type+" "+Description +" "+Chemin ;
ArrayList<String> p = new ArrayList<String>();
p.add(trace);
System.out.println(p);
}
}
catch(IOException e) {
e.printStackTrace();
}
}
Without knowing the exception I can guess one of the potential issue is in these lines:-
String [] splitted = str.split("\\|");
String b = splitted[1].trim();
String c = splitted[2].trim();
String d = splitted[3].trim();
You are accessing splitted without checking if it is null or size so you may run into ArrayIndexOutOfBound exception if splitted length is less than 3. So modify the code this way-
String [] splitted = str.split("\\|");
if(splitted!=null && splitted.length==3){
String b = splitted[0].trim();
String c = splitted[1].trim();
String d = splitted[2].trim();
}
The NullPointerException you get now that you've fixed the ArrayIndexOutOfBound is because of the test you use in your while loop:
while(reader != null)
{
...
}
reader will always be non-null so this loop will never end. You need to test if
reader.readLine()
returns null (indicating EOF).
I guess you get an ArrayIndexOutOfBoundException, right?
(You need to tell us, what Exception you receive)
The problem could be in the following lines. You should check the size of the array and not just "hope" that it has three parts.
String b = splitted[1].trim();
String c = splitted[2].trim();
String d = splitted[3].trim();