Java exception error when using Scanner - java

Can someone please help me see what the problem is. I realise that using
String kind = sc.next();
might bring a problem. if that's the issue how do i fix it. Thank you in advance. Here is the code.
import java.io.*;
import java.util.*;
public abstract class Account {
protected static AccountNumber accountNumber;
protected Customer customer = null; // not to be used yet
public abstract MeterNumber[] getMeterNumbers();
public abstract boolean exists(String meterNumber, String tariff);
public static Account load(Scanner sc) {
while (sc.hasNextLine()) {
AccountNumber accountNumber = AccountNumber.fromString(sc.nextLine());
String kind = sc.next();
sc.nextLine();
if (kind.equals("D")) {
return new DomesticAccount(sc, accountNumber);
} else {
return new CommercialAccount(sc, accountNumber);
}
} {
return null;
}
}
}
The code in main is as follows.
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
public class Testt {
public static void main(String[] args) {
Account.load(new Scanner("Accounts3.txt"));
Map <AccountNumber, String> map1 = new HashMap <AccountNumber, String>();
map1.put(Account.accountNumber, "hello");
System.out.println(map1);
}
}
and this is the error I am getting.
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at Account.load(Account.java:20)
at Testt.main(Testt.java:14)

Your are creating scanner on string object. Which is just "Accounts3.txt". Which is just one line.
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#Scanner(java.lang.String)
I think you need to create scanner on file.
Refere this:
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#Scanner(java.io.File)
So your main method will create scanner like this:
Account.load(new Scanner(new java.io.File("Accounts3.txt")));

Related

Access to method of another class in the same package is not possible

I cannot access the static method of a class that is in the same package. I get the class name displayed in the auto-complete, but the method doesn't want to work.
I have already tried the following functionality of intellij without success.
"File" > "Invalidate Caches / Restart" > "Invalidate and Restart"
Method:
package de.elektriker_lifestyle.reducedcoffee;
import java.util.List;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import com.opencsv.*;
public class csvReader {
private static final char SEPARATOR = ',';
public static void updateCSV(String input, String output, String replace, int row, int col) throws IOException {
CSVReader reader = new CSVReader(new FileReader(input),SEPARATOR);
List<String[]> csvBody = reader.readAll();
csvBody.get(row)[col]=replace;
reader.close();
CSVWriter writer = new CSVWriter(new FileWriter(output),SEPARATOR,' ');
writer.writeAll(csvBody);
writer.flush();
writer.close();
}
}
Here I want to use the method:
package de.elektriker_lifestyle.reducedcoffee;
public class test {
csvReader.updateCSV(...);
}
Screenshots:
https://i.imgur.com/LSRmuHy.png
https://i.imgur.com/crSqGoQ.png
https://i.imgur.com/O3Mdpa1.png
The following error appears "Cannot resolve symbol 'updateCSV'".
This code is not valid Java, you cannot call a method from the body of a class, a method call has to be part of some kind of initializer (such as a static field initializer or static block) or a method.
public class test {
csvReader.updateCSV(...);
}
You need to call the static method csvReader.updateCSV with all of the required arguments:
csvReader.updateCSV("1", "2", "3", 4, 5);
Use the code below as a guide:
import java.util.List;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.CSVWriter;
public class csvReader {
private static final char SEPARATOR = ',';
public static void updateCSV(String input, String output, String replace, int row, int col) throws IOException {
CSVReader reader = new CSVReader(new FileReader(input),SEPARATOR);
List<String[]> csvBody = reader.readAll();
csvBody.get(row)[col]=replace;
reader.close();
CSVWriter writer = new CSVWriter(new FileWriter(output),SEPARATOR,' ');
writer.writeAll(csvBody);
writer.flush();
writer.close();
}
public static void main(String[] args) throws IOException {
csvReader.updateCSV("1", "2", "3", 4, 5);
}
}
As the previous answer states, you cannot call the method in the body of a class, all method executions should be inside another method this propagated until the main method.
Also the call you are doing is missing some parameters of your method declaration.
By last if you want your static method to get executed always on your class you should do it on the class constructor:
public class test {
public test () {
csvReader.updateCSV(...);
}
}
`
That way each time a test object gets created your static method will get executed.
import de.elektriker_lifestyle.reducedcoffee.csvReader.java in the test class above the public class test{}

Getting a method not found in class, when I already have the method declared?

I'm trying to create objects of the classes I have in the main method, I'm implementing the lazy simpleton pattern, but I keep getting the error cannot find symbol in class. I've checked to see if I've written the import package statements correctly as well.
This is my main class
package control;
import java.io.File;
import java.io.FileNotFoundException;
import model.ApplicationModel;
import java.util.* ;
import model.Shop;
import view.ApplicationViewer;
import model.ApplicationModel;
public class ApplicationControl {
public static void main (String[] args) throws FileNotFoundException{
ApplicationModel apm = new ApplicationModel.getInstance();
}
}
This is my Singleton class ApplicationModel
package model;
// needed for ArrayLists
import java.io.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ApplicationModel {
private static ApplicationModel instance = null;
private ApplicationModel()
{
}
public static ApplicationModel getInstance (){
if (instance == null){
instance = new ApplicationModel();
}
return instance;
}
private List<Shop> shops = new ArrayList<Shop>();
public List<Shop> getShops(){
return this.shops;
}
public void setShops(List<Shop> shops){
this.shops = shops;
}
public Shop createShop(String csvString){
String[] attributes = csvString.split(",");
Shop shop = new Shop(attributes[0],attributes[1],attributes[2],
attributes[3],attributes[4]);
return shop;
}
public List<Shop> readShops(String shopFileName){
ApplicationModel am = new ApplicationModel();
List<Shop> shopList = new ArrayList<>();
try{
Scanner naughty = new Scanner(new File(shopFileName));
if (naughty.hasNext()) naughty.nextLine();
while(naughty.hasNext()){
shopList.add(am.createShop(naughty.nextLine()));
}
} catch (FileNotFoundException ex) {
Logger.getLogger(ApplicationModel.class.getName()).log(Level.SEVERE, null, ex);
}
return shopList;
}
public String printShops(){
String listOfShops ="";
for(Shop shop : shops ){
listOfShops = listOfShops +'\n'+ shop.toString().trim() + '\n';
}
return listOfShops.trim();
}
}
Whenever I type in ApplicationModel in the main class, the import statement error stating that the import has not been used goes away too, I'm not sure what's wrong (I'm using netbeans). Can anyone help?
Remove "new" from your code:
ApplicationModel apm = ApplicationModel.getInstance();
Being static, getInstance() is a class method (not an instance method). This syntax is how you call class methods.

Java decoupling issue

am new to Java. I am trying to decouple the Responder class from the WeatherSystem Class. But I get an error at Public NewResponder in the Responder class (invalid method declaration; return type required), I am really stuck at this point. I have tried changing all the class points at NewResponder and responder but can't rectify it. Could anyone point out why I am getting this issue, please?
(I also have InputReader class but that's not included below).
WeatherSystem Class
import java.util.HashSet;
public class WeatherSystem
{
private InputReader reader;
private NewResponder responder;
public WeatherSystem(NewResponder responder)
{
reader = new InputReader();
this.responder = new Responder();
}
public void start()
{
boolean finished = false;
printWelcome();
while(!finished) {
HashSet<String> input = reader.getInput();
if(input.contains("exit")) {
finished = true;
}
else {
String response = this.responder.generateResponse(input);
System.out.println(response);
}
}
printGoodbye();
.............................................
Class Responder
import java.util.HashMap;
import java.util.HashSet;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
import WeatherSystem.NewResponder
public class Responder implements NewResponder
{
private HashMap<String, String> responseMap;
private ArrayList<String> defaultResponses;
private Random randomGenerator;
public NewResponder()
{
responseMap = new HashMap<>();
defaultResponses = new ArrayList<>();
fillResponseMap();
fillDefaultResponses();
randomGenerator = new Random();
}
public String generateResponse(HashSet<String> words)
{
for (String word : words) {
String response = this.responseMap.get(word);
if(response != null) {
return response;
}
}
return pickDefaultResponse();
....................................................
You really need to check whether you need interface NewResponder inside WeatherSystem. Which you are implementing in Responder class with wrong constructor name.

Array with a blank reult

why can execute my code without any issues and it gives me the correct results.
package com.opennlp.demo;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Set;
import opennlp.tools.cmdline.parser.ParserTool;
import opennlp.tools.parser.Parse;
import opennlp.tools.parser.Parser;
import opennlp.tools.parser.ParserFactory;
import opennlp.tools.parser.ParserModel;
public class ParserTest {
public static Set<String> nounPhrases = new HashSet<>();
private static String line = "I need a PHP note if";
public void getNounPhrases(Parse p) {
if (p.getType().equals("NN") || p.getType().equals("NNS") || p.getType().equals("NNP") || p.getType().equals("NNPS")) {
nounPhrases.add(p.getCoveredText());
//System.out.println(p.getCoveredText());
}
for (Parse child : p.getChildren()) {
getNounPhrases(child);
System.out.println(child.toString()+"lol");
}
}
public void parserAction() throws Exception {
InputStream is = new FileInputStream("en-parser-chunking.bin");
ParserModel model = new ParserModel(is);
Parser parser = ParserFactory.create(model);
Parse topParses[] = ParserTool.parseLine(line, parser, 1);
for (Parse p : topParses){
//p.show();
getNounPhrases(p);
}
}
public static void main(String[] args) throws Exception {
new ParserTest().parserAction();
System.out.println("List of Noun Parse : "+nounPhrases);
}
}
below is my second code.. it gives me a blank Array in console.I removed main method from above class and I tried to print the nounPhrases inside another class. it shows a blank array. I think in second code my parserAction method is not executing. How can I do execute that method without a main method in another class ?
my second code
package com.opennlp.demo;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Set;
import opennlp.tools.cmdline.parser.ParserTool;
import opennlp.tools.parser.Parse;
import opennlp.tools.parser.Parser;
import opennlp.tools.parser.ParserFactory;
import opennlp.tools.parser.ParserModel;
public class ParserTest {
public static Set<String> nounPhrases = new HashSet<>();
//private static String line = "i need a Java book which has JSP also";
private static String line = "I need a PHP note if";
public void getNounPhrases(Parse p) {
if (p.getType().equals("NN") || p.getType().equals("NNS") || p.getType().equals("NNP") || p.getType().equals("NNPS")) {
nounPhrases.add(p.getCoveredText());
//System.out.println(p.getCoveredText());
}
for (Parse child : p.getChildren()) {
getNounPhrases(child);
System.out.println(child.toString()+"lol");
}
}
public void parserAction() throws Exception {
InputStream is = new FileInputStream("en-parser-chunking.bin");
ParserModel model = new ParserModel(is);
Parser parser = ParserFactory.create(model);
Parse topParses[] = ParserTool.parseLine(line, parser, 1);
for (Parse p : topParses){
//p.show();
getNounPhrases(p);
}
}
}
I called the nounPhrases in another class like below. But it shows a blank result. How to fix this ? I need to do this without a main method in this class.
ParserTest pt = new ParserTest();
pt.parserAction();
System.out.println(ParserTest.nounPhrases);

Reversing ArrayList<String>

All im trying to do is reverse the ArrayList. Is there a way I could do it through the toString as well or should I just create a method like I did. Im so close, any answers will help! Thanks!
package edu.purse.test;
java.util.ArrayList;
import java.util.Collections;
public class Purse
{
ArrayList<String> coins = new ArrayList<String>();
public Purse()
{
}
public void addCoin(String coinName)
{
coins.add(coinName);
}
public String toString()
{
return "Purse" + coins.toString();
}
public ArrayList<String> getReversed(ArrayList<String> coins)
{
ArrayList<String> copy = new ArrayList<String>(coins);
Collections.reverse(copy);
return copy;
}
}
TESTERCLASS
package edu.purse.test;
import java.util.Collections;
import java.util.List;
public class PurseTester {
public static void main(String[] args) {
Purse p = new Purse();
p.addCoin("Quarter");
p.addCoin("Dime");
p.addCoin("Nickel");
p.addCoin("Penny");
System.out.println(p.toString());
p.getReversed(coins);
}
}
The method
p.getReversed(coins);
returns a reversed list. You can just print it out
System.out.println(p.getReversed(coins));
Note that you are getting a copy of your instance's list, reversing that, and then returning it. If you want to preserve the change, simple call Collections.reverse() on the original, coins.

Categories

Resources