I am writing Service for adding new Menu Items to Menu. Everything works fine with the tutorial which guided how to stimulate the System.in in Junit test.
However, one parameter of Menu Items need to set to float value is Menu Item price. As a result, the String input I provided by ByteArrayInputStream and System.setIn doesn't seem to change the String values to Float value as I expected.
This is my service code:
public class DailyMenuServicesImpl implements DailyMenuServices {
private MenuPrinter menuPrinter;
public DailyMenuServicesImpl(){
this.menuPrinter = new MenuPrinterImpl();
}
#Override
public DailyMenu addMenuItemsToMenu(DailyMenu dailyMenu) {
Scanner scanner = new Scanner(System.in);
MenuItem menuItem = new MenuItem();
List<MenuItem> menuItemList = dailyMenu.getMenuItemList();
try {
System.out.print("\nInsert menu item name: ");
menuItem.setNames(scanner.nextLine());
System.out.print("Insert menu item description: ");
menuItem.setDescription(scanner.nextLine());
System.out.print("Insert menu item image: ");
menuItem.setImage(scanner.nextLine());
System.out.print("Insert menu item price:");
menuItem.setPrice(scanner.nextFloat()); // this is the problem everything above works fine.
menuItemList.add(menuItem);
dailyMenu.setMenuItemList(menuItemList);
}catch (IllegalStateException exception){
System.out.println(exception.getMessage());
}catch (InputMismatchException exception){
System.out.println(new InputMismatchException("Menu item price must be number !!!").getMessage());
}
return dailyMenu;
}
}
And here is my unit test:
#RunWith(MockitoJUnitRunner.class)
public class DailyMenuServiceTest {
private MenuPrinter menuPrinter;
private DailyMenuServices dailyMenuServices;
private final InputStream systemIn = System.in;
private final PrintStream systemOut = System.out;
private ByteArrayInputStream testIn;
private ByteArrayOutputStream testOut;
#Before
public void init(){
dailyMenuServices = new DailyMenuServicesImpl();
testOut = new ByteArrayOutputStream();
menuPrinter = new MenuPrinterImpl();
System.setOut(new PrintStream(testOut));
}
#After
public void restoreSystemInputOutput(){
System.setIn(systemIn);
System.setOut(systemOut);
}
#Test
public void whenAddNewMenuItemsToMenu_returnNewDailyMenu(){
List<MenuItem> menuItemList = new ArrayList<>();
DailyMenu dailyMenu = new DailyMenu(menuItemList);
provideInput("Pizza\nGood\nItaly\n4.56f");
dailyMenu = dailyMenuServices.addMenuItemsToMenu(dailyMenu);
menuPrinter.printMenu(dailyMenu);
String expected = "Names: Pizza - Price: 4.56$";
assertEquals(expected,testOut.toString());
}
private void provideInput(String data){
testIn = new ByteArrayInputStream(data.getBytes());
System.setIn(testIn);
}
So how I can set the Menu Item price parameter as Float values if I use the ByteArrayInputStream like tutorial? All your supports are big helps to me.
You can use the System Rules to pass in the user input from the Java.lang.System I believe.You can find more information here: https://stefanbirkner.github.io/system-rules
Keep in mind this is an external Library
Syntax Should be
import java.util.Scanner;
public class Summarize {
public static int sumOfNumbersFromSystemIn() {
Scanner scanner = new Scanner(System.in);
int firstSummand = scanner.nextInt();
int secondSummand = scanner.nextInt();
return firstSummand + secondSummand;
}
}
import static org.junit.Assert.*;
import static org.junit.contrib.java.lang.system.TextFromStandardInputStream.*;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.TextFromStandardInputStream;
public class SummarizeTest {
#Rule
public final TextFromStandardInputStream systemInMock
= emptyStandardInputStream();
#Test
public void summarizesTwoNumbers() {
systemInMock.provideLines("1", "2");
assertEquals(3, Summarize.sumOfNumbersFromSystemIn());
}
}
Related
I'm attempting collect all the methods in a Java file using the Eclipse AST package. I believe that I have the CompilationUnit created successfully. However when I attempt to use a visitor to collect the information it doesn't go past the main() method of the file I'm testing.
public void parseCode(String fileName) {
String strSource = "";
try {
strSource = codeToString(fileName);
} catch (Exception e) {
e.printStackTrace();
}
ASTParser parser = ASTParser.newParser(AST.JLS8);
parser.setSource(strSource.toCharArray());
parser.setKind(ASTParser.K_COMPILATION_UNIT);
final CompilationUnit cu = (CompilationUnit) parser.createAST(new NullProgressMonitor());
SCTVisitor v = new SCTVisitor();
cu.accept(v);
System.out.println(v.m);
}
public class SCTVisitor extends ASTVisitor{
List<SimpleName> m = new ArrayList<SimpleName>();
SCTVisitor(){
System.out.println("What is love");
}
#Override public boolean visit(MethodInvocation node) {
this.m.add(node.getName());
return true;
}
}
This is part of the file I'm using to test:
import java.util.Map;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.UIManager;
public class WordCount {
public static void main(String[] args) {
System.out.println("Cheese");
countWordsViaGUI();
}
// allow user to pick file to exam via GUI.
// allow multiple picks
public static void countWordsViaGUI() {
setLookAndFeel();
try {
Scanner key = new Scanner(System.in);
do {
System.out.println("Opening GUI to choose file.");
Scanner fileScanner = new Scanner(getFile());
Stopwatch st = new Stopwatch();
st.start();
ArrayList<String> words = countWordsWithArrayList(fileScanner);
st.stop();
System.out.println("time to count: " + st);
System.out.print("Enter number of words to display: ");
int numWordsToShow = Integer.parseInt(key.nextLine());
showWords(words, numWordsToShow);
fileScanner.close();
System.out.print("Perform another count? ");
} while(key.nextLine().toLowerCase().charAt(0) == 'y');
key.close();
}
catch(FileNotFoundException e) {
System.out.println("Problem reading the data file. Exiting the program." + e);
}
}
My results are:
[println, countWordsViaGUI]
My expected results are:
[println, countWordsViaGUI, setLookAndFeel, scanner, println, getFile, Scanner, ...]
Please let me know if you have any insight into this problem.
Problem Defined: I store bookname and bookauthor variable data in file using tostring to buffer writer, When i run program next time program read the file but not to store data back to the variable
Please write read code and and variable data storing from file in JAVA
...........................................................................................................................................................
Three Classes One is Main Class,Second is filewriting class and One Class having book add function.Source Code is given here
import java.util.Scanner;
import java.io.*;
public class AddBook extends Filewriting{
public int add;
public AddBook(int add){this.add=add;}
public String bookname[] = new String[15];
public String bookauthor[] = new String[15];
public int price[] = new int[15];
public void addbook(){
for(int i=0;i<add;i++){
System.out.println("Enter the Book Title:");
Scanner input=new Scanner(System.in);
bookname[i]=input.nextLine();
System.out.println("Enter the Book Author:");
Scanner scan=new Scanner(System.in);
bookauthor[i]=input.nextLine();
System.out.println("Enter the Book Price:");
Scanner input1=new Scanner(System.in);
price[i]=input1.nextInt();
}
}
public String toString(int j)
{
return String.format("BookName:%s%nBookAuthor:%s%nBookPrice:%d%n%n................................................................................................................................%n",bookname[j],bookauthor[j],price[j]);
}
}
import java.util.*;
import java.io.*;
public class Filewriting {
public int add;
public void filewriting(){
System.out.println("How many Books you want to added:");
Scanner in=new Scanner(System.in);
add=in.nextInt();
try{
File file = new File("Hello1.txt");
// creates New file
file.createNewFile();
Writer writer = new FileWriter("Hello1.txt",true);
BufferedWriter bufferWriter = new BufferedWriter(writer);
AddBook obj=new AddBook(add);
obj.addbook();
for ( int i = 0; i < add; i++){
// bufferWriter.write(obj.bookname[i] + obj.bookauthor[i] +obj.price[i]);
bufferWriter.write(obj.toString(i));
}
bufferWriter.close();
}
catch(Exception e)
{
}
}
/* // Creates a FileReader Object
FileReader fr = new FileReader(file);
char [] a = new char[50];
fr.read(a); // reads the content to the array
for(char c : a)
System.out.print(c); // prints the characters one by one
fr.close(); */
}
import java.util.Scanner;
import java.io.*;
public class Test{
public static void main(String args[]){
System.out.println("Enter 1 to Add Books:");
System.out.println("Enter 2 to Check Store Books again in Variable:");
Scanner input=new Scanner(System.in);
int i=input.nextInt();
if(i==1){
System.out.println("You Press B");
Filewriting fw=new Filewriting();
fw.filewriting();
}
if(i==2)
{
Filewriting fw=new Filewriting();
AddBook obj=new AddBook(fw.add);
for ( int j = 0; j < 2; j++) // for storing 2 variables data
{
System.out.println(obj.bookname[j]); // just check bookname,shows null
}
}
// Please write code that we read the file as well as data is stored again in Variables
}
}
I see You can write Data in File as not well.From your Code it is impossible to Store data in your variables.You must set and get Methods in your program in order to store variables.Following Program Code is help you to storing file data to variable perfectly.
................................................................................
public class Book {
public String name;
public String author;
public int price;
public Book(){
this("","",0);
}
public Book(String name,String author,int price){
setName(name);
setAuthor(author);
setPrice(price);
}
public void setName(String name){
this.name= name ;
}
public void setAuthor(String author){
this.author = author ;
}
public void setPrice(int price){
this.price = price ;
}
public String getName(){
return name;
}
public String getAuthor(){
return author;
}
public int getPrice(){
return price;
}
}
import java.io.*;
import java.util.*;
public class ReadText {
Scanner input,a;
public void OpenBook(){
File f = new File("Hello1.txt");
if ( f.exists()){
System.out.println("Welcome Ur File IS Open....."+f);
}
else
{
System.out.println("Error... File DOes not exits");
System.exit(1);
}
try {
input = new Scanner(new File("Hello1.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public void ReadBook(){
Book b = new Book();
while((input.hasNext())){
b.setName(input.nextLine());
b.setAuthor(input.nextLine());
b.setPrice(Integer.parseInt(input.nextLine()));
System.out.printf("Book Name:%s\nBook Author:%s\nBook Price:%d\n",b.getName(),b.getAuthor(),b.getPrice());
}
}
}
I'm getting a ClassCastException when I deserialize my object from a file. When I check the file the object is there, so I know it's being serialized correctly. For some reason the code breaks when trying to retrieve the object. The idea is to allow the user to check, by date, all the workouts they've recorded in their log. Also, I've tried implementing a comparator, but I kept getting the same error and I'm all out of ideas. Any help would be much appreciated.
Here is the code that is causing the trouble:
case Logger.CHECK_KEY:
//TODO
try {
workoutLog = (WorkoutLog) SerializationUtil.deserialize(file);
System.out.println("Deserializing from:..." + file.getName());
}
Here is the workoutLog class:
public class WorkoutLog implements Serializable{
public TreeMap < String , Workout > mWorkoutLog;
// thia is the actual Workoutlog
public WorkoutLog(){
mWorkoutLog = new TreeMap<>();
}
//the string key will be the workouts formatted date
public TreeMap < String, Workout> getWorkoutLog(){
return mWorkoutLog;
}
I'm including the body of the code for context
package com.alejandro;
import com.alejandro.Utilities.SerializationUtil;
import com.alejandro.model.Exercise;
import com.alejandro.model.Workout;
import com.alejandro.model.WorkoutLog;
import com.sun.istack.internal.NotNull;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.TreeMap;
public class Logger {
public static final String COMPLETE_KEY = "COMPLETE";
public static final String INCOMPLETE_KEY = "INCOMPLETE";
public static final String ADD_KEY = "ADD";
public static final String CHECK_KEY = "CHECK";
public static final String EXIT_KEY = "EXIT";
public static void main(String[] args) throws IOException, ClassNotFoundException {
Logger logger = new Logger();
WorkoutLog workoutLog = new WorkoutLog();
Workout workout = new Workout();
File file = new File("workout.txt");
//im going to need to ask if the user wants to add a workout, close the program, or select a workout
String userInput = checkUserIntention();
//the switch statement goes through all the possible user inputs
switch(userInput){
case Logger.ADD_KEY:
printInstructions();
do{
logger.promptForExerciseData(workout);
}while(!checkIfUserIsDone());
workoutLog.getWorkoutLog().put(workout.getDate(),workout);
SerializationUtil.serialize(workoutLog,file);
System.out.println("Workout saved in..." +file.getName());
break;
case Logger.CHECK_KEY:
//TODO
try {
workoutLog = (WorkoutLog) SerializationUtil.deserialize(file);
System.out.println("Deserializing from:..." + file.getName());
System.out.println(workoutLog.getWorkoutLog().keySet()+"");
} catch(EOFException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch(ClassCastException E){
E.printStackTrace();
}
break;
case Logger.EXIT_KEY:
System.out.println("\nExiting program...");
break;
}
}
//I'm using this method to explain to the user how to use the program
protected static void printInstructions(){
System.out.println("\nWelcome to Mr.Strong!\n");
System.out.println("This program was developed to help powerlifters keep a log of their lifts.\n");
System.out.println("Because of this, the program will only recognize the following lifts:\n");
System.out.println("Squat, Bench, Deadlift, Press.\n");
System.out.println("The program is case-sensitive, make sure the information is entered as stated above.\n");
}
//this method asks the user for information about the lifts stores them in a workout object
//the methods used here are all organized throught the page, its just to keep things cleaner and separate
protected void promptForExerciseData(Workout workout){
Exercise exercise = new Exercise();
askForExerciseIdentity(exercise);
askForNumsRelLifts(exercise);
workout.getExerciseList().add(exercise);
}
//this will check to see if the user is done inputting the exercises he did, if he finished the program ends.
protected static boolean checkIfUserIsDone(){
Scanner scanner = new Scanner(System.in);
boolean isUserDone = false;
System.out.println("\nEnter: 'complete'" + ", if you are done. " +
"If not, enter:'incomplete " + ".\n");
String answer = scanner.nextLine();
if(answer.trim().toUpperCase().equals(Logger.COMPLETE_KEY)){
isUserDone = true;
} else if(answer.trim().toUpperCase().equals(Logger.INCOMPLETE_KEY)){
isUserDone = false;
} else{
checkIfUserIsDone();
}
return isUserDone;
}
//check if user wants to add, review, or close
protected static String checkUserIntention(){
String answer = "a";
Scanner scanner = new Scanner(System.in);
System.out.println("\nPlease choose an option:\n" +
"1-) Add a workout. Enter 'Add'.\n" +
"2-) Check a workout Enter 'Check'.\n" +
"3-) Exit the program. Enter 'Exit'\n");
answer = scanner.nextLine();
if(answer.trim().toUpperCase().equals(Logger.ADD_KEY) ||
answer.trim().toUpperCase().equals(Logger.CHECK_KEY)||
answer.trim().toUpperCase().equals(Logger.EXIT_KEY)){
return answer.toUpperCase();
}else{
System.out.println("Incorrect input.");
checkUserIntention();
}
return answer;
}
//all of this part is asking for the exercise data
//this is the part that asks for exercise id
protected void askForExerciseIdentity(Exercise exercise){
Scanner scanner = new Scanner(System.in);
do{
System.out.println("\nEnter a lift:\n");
String exerciseIdentity = scanner.nextLine();
if(exerciseIdentity.equals(exercise.SQUAT_KEY)){
exercise.setExerciseIdentity(exercise.SQUAT_KEY);
}else if(exerciseIdentity.equals(exercise.PRESS_KEY)){
exercise.setExerciseIdentity(exercise.PRESS_KEY);
}else if(exerciseIdentity.equals(exercise.BENCH_KEY)){
exercise.setExerciseIdentity(exercise.BENCH_KEY);
}else if(exerciseIdentity.equals(exercise.DEADLIFT_KEY)){
exercise.setExerciseIdentity(exercise.DEADLIFT_KEY);
}else {
exercise.setExerciseIdentity(null);
System.out.println("Please enter a valid exercise.");
}}while(exercise.getExerciseIdentity() == null);
}
//this is the part that aks for numbers
protected void askForNumsRelLifts(Exercise exercise){
exercise.setWeightUsed(askForWeightUsed());
exercise.setNumOfReps(askForNumOfReps());
exercise.setNumOfSets(askForNumOfSets());
}
protected double askForWeightUsed(){
Scanner scanner = new Scanner(System.in);
double weightUsed;
do{
try{
System.out.println("\nEnter weight used:\n");
weightUsed = Double.parseDouble(scanner.nextLine());
}catch(NumberFormatException e){
System.out.println("\nPlease enter a valid number\n");
weightUsed = 0;
}
} while(weightUsed == 0);
return weightUsed;
}
protected double askForNumOfSets(){
Scanner scanner = new Scanner(System.in);
double numOfSets;
do{
try{
System.out.println("\nEnter sets done:\n");
numOfSets = Double.parseDouble(scanner.nextLine());
}catch(NumberFormatException e){
System.out.println("\nPlease enter a valid number\n");
numOfSets = 0;
}
}while(numOfSets == 0);
return numOfSets;
}
protected double askForNumOfReps(){
Scanner scanner = new Scanner(System.in);
double reps;
do{
try{
System.out.println("\nEnter reps done:\n");
reps = Double.parseDouble(scanner.nextLine());
} catch(NumberFormatException e){
System.out.println("\nPlease enter a valid number\n");
reps = 0;
}
}while(reps == 0);
return reps;
}
}
Here is workout included:
public class Workout implements Serializable{
protected ArrayList<Exercise> mExerciseList;
protected Date mDateCreated;
public Workout(){
mExerciseList = new ArrayList<>();
mDateCreated = new Date();
}
public ArrayList<Exercise> getExerciseList(){
return mExerciseList;
}
public String getDate(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
return sdf.format(mDateCreated);
}}
Here is the seralizationutil:
import com.alejandro.model.WorkoutLog;
import java.io.*;
public class SerializationUtil{
public static Object deserialize(File filename) throws IOException, ClassNotFoundException{
FileInputStream fis = new FileInputStream(filename);
Object obj = new Object();
BufferedInputStream bis = new BufferedInputStream(fis);
ObjectInputStream ois = new ObjectInputStream(bis);
while(fis.available()>0){
obj = ois.readObject();
}
ois.close();
return obj;
}
public static void serialize(Object object, File filename) throws IOException{
FileOutputStream fos = new FileOutputStream(filename);
BufferedOutputStream bos = new BufferedOutputStream(fos);
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(object);
oos.close();
}}
Here is what the compiler gives me:
java.lang.ClassCastException: java.lang.Object cannot be cast to com.alejandro.model.WorkoutLog
at com.alejandro.Logger.main(Logger.java:56)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
just try this simple example, i have modified your code extensively
one more thing, I dont know what implementation you have under SerializationUtil so i created my own implementation
My example works without any issue
package week4;
import java.io.Serializable;
import java.util.TreeMap;
public class WorkoutLog implements Serializable {
public TreeMap < String , Workout > mWorkoutLog;
// thia is the actual Workoutlog
public WorkoutLog(){
mWorkoutLog = new TreeMap<>();
}
//the string key will be the workouts formatted date
public TreeMap < String, Workout> getWorkoutLog(){
return mWorkoutLog;
}
}
package week4;
import java.io.Serializable;
public class Workout implements Serializable {
String date = "2016-01-13";
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
package week4;
import java.io.File;
import java.io.IOException;
public class TestWorkOut {
public static void main(String[] args) throws IOException, ClassNotFoundException {
WorkoutLog workoutLog = new WorkoutLog();
Workout workout = new Workout();
/* I had path to workout.txt as D:\\workout.txt*/
File file = new File("D:\\workout.txt");
workoutLog.getWorkoutLog().put(workout.getDate(),workout);
SerializationUtil.serialize(workoutLog,file);
System.out.println("Workout saved in..." +file.getName());
workoutLog = (WorkoutLog) SerializationUtil.deserialize(file);
System.out.println("Deserializing from:..." + file.getName());
System.out.println(workoutLog.getWorkoutLog().keySet()+"");
}
}
package week4;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SerializationUtil {
public static void serialize(WorkoutLog workoutLog, File filename) {
FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
fos = new FileOutputStream(filename);
out = new ObjectOutputStream(fos);
out.writeObject(workoutLog);
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static WorkoutLog deserialize(File filename) {
FileInputStream fis = null;
ObjectInputStream in = null;
WorkoutLog workout = null;
try {
fis = new FileInputStream(filename);
in = new ObjectInputStream(fis);
workout = (WorkoutLog) in.readObject();
in.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return workout;
}
}
Output
Workout saved in...workout.txt
Deserializing from:...workout.txt
[2016-01-13]
I know that this question has been addressed before,but i simply cannot find the answer no matter how hard i try.
I am trying to serialize and deserialize objects in Java. I am having problems in the deserialization. I do not get the values that were entered, but something along the lines of prueba.Estudiantes#1bd7848. Why do i get this instead of the actual values typed in?
Here is my code
package prueba;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Prueba {
public static void main(String[] args) throws FileNotFoundException,IOException, ClassNotFoundException {
File file = new File("f.txt");
List <Estudiantes> lista = new ArrayList<>();
boolean continuar = true;
while (continuar == true){
Estudiantes es = new Estudiantes();
System.out.println("Ingrese nombre");
Scanner kb = new Scanner(System.in);
es.nombre = kb.nextLine();
System.out.println("Ingrese Apellido");
Scanner kb1 = new Scanner(System.in);
es.apellido = kb1.nextLine();
System.out.println("Ingrese NĂºmero");
Scanner kb2 = new Scanner(System.in);
es.numero = kb2.nextInt();
lista.add(es);
FileOutputStream fo = new FileOutputStream(file);
ObjectOutputStream output = new ObjectOutputStream(fo);
for (Estudiantes est: lista){
output.writeObject(est);
}
output.close();
fo.close();
FileInputStream fi = new FileInputStream(file);
ObjectInputStream input = new ObjectInputStream(fi);
ArrayList<Estudiantes> est2 = new ArrayList<Estudiantes>();
try {
while (true){
Estudiantes s = (Estudiantes)input.readObject();
est2.add(s);
}
}
catch (EOFException ex){}
for (Estudiantes s :est2){
System.out.println(s);
fi.close();
input.close();
}
System.out.println("0 para salir; 1 para continuar");
Scanner kb3 = new Scanner(System.in);
int rev = kb3.nextInt();
if (rev == 0){
continuar = false;
System.out.println("Hasta Luego");
}
}
}
}
And here is my Estudiantes class
package prueba;
import java.io.Serializable;
public class Estudiantes implements Serializable{
String nombre, apellido;
int numero;
}
Thanks
I do not get the values that were entered, but something along the lines of prueba.Estudiantes#1bd7848
That's what you get when you explicitly or implicitly call toString() on an object whose class hasn't overridden it.
It isn't evidence that you have a problem.
I think if you are getting the values like prueba.Estudiantes#1bd7848 you are its already been deserialized. You just have to override the toString() properly to get the output. Not sure if this helps
When you try to print your class when reading back the objects you previously wrote you have to implement the toString() method from the Object class here is what I mean.
Change your class to this:
public class Estudiantes implements Serializable {
private static final long serialVersionUID = 123L; // has to be unique
String nombre, apellido;
int numero;
#Override
public String toString() {
System.out.println("first name: " + nombre);
System.out.println("last name: " + apellido);
System.out.println(numero);
return // a string you want to print
}
}
I'm trying to add a list of phrases from the text file "ListOfElectronics.txt", to the ArrayList "electronics".
I'm getting an error here: electronics.add(fileIn.nextLine());
It's saying "no suitable method found for add(java.lang.String)"
import java.util.Scanner;
import java.util.ArrayList;
import java.io.*;
/***
*
*
*
*/
public class Driver
{
public static void main(String[] args)
{
System.out.println("\f");
ArrayList<Electronics> electronics = new ArrayList<Electronics>();
Scanner stdIn = new Scanner(System.in);
Scanner fileIn;
try
{
fileIn = new Scanner(new FileReader("ListOfElectronics.txt"));
while (fileIn.hasNextLine())
{
electronics.add(fileIn.nextLine());
}
fileIn.close();
}
catch (FileNotFoundException e)
{
System.out.println("Error: " + e.getMessage());
}
}
}
Replace
ArrayList<Electronics> electronics = new ArrayList<Electronics>();
with
ArrayList<String> electronics = new ArrayList<>();
Otherwise, it's expecting you to add objects of a class of a type called Electronics.
If you do have a class called Electronics, that you're looking to add to the Arraylist, and if it has a constructor that calls for a String, you can replace the add string with:
electronics.add(new Electronics(fileIn.nextLine()));
If your Electronics class looks like this
public class Electronics {
private string name;
public Electronics(String name) {
this.name = name;
}
}
then you could just replace:
while (fileIn.hasNextLine())
{
electronics.add(fileIn.nextLine());
}
with
while (fileIn.hasNextLine())
{
Electronics electronics = new Electronics(fileIn.nextLine();
electronics.add(electronics);
}