Classes and Objects with ArrayList [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I am trying to create a program that takes a file name as a parameter, opens that file, reads in all of the text in that file (about 1 paragraph) and then give the user a few options to manipulate the paragraph.
I am having trouble with the scanner which asks the user for the command. For example, if the user presses 1, I want it to take the user to public void palindrome (), but it won't compile.
I haven't written in the code yet for public void palindrome, but there shouldn't be any compiling errors.
import java.util.ArrayList;
import java.util.Scanner;
import java.util.*;
import java.io.File;
public class Test {
public static void main (String [] args) {
Scanner scanner = new Scanner(new File(args[0]));
ArrayList<String> strings = new ArrayList<String>();
while( scanner.hasNext() ) {
strings.add( scanner.next() );
}
ArrayList<String> a = new ArrayList<String>(strings);
while (true) {
System.out.println ("\nWhat would you like to do? Here are your options: \nPress 1 to Print all palindromes \nPress 2 to Replace any letter \nPress 3 to remove all occurences of a word \nPress 4 to exit\n");
Scanner s = new Scanner(System.in);
String command = s.next();
if (command.equals("1")) {
a.palindrome();
} else if (command.equals("2")){
a.letter();
} else if (command.equals("3")){
a.word();
} else if (command.equals("4")){
System.exit(0);
}
}
}
public void palindrome () {
}
public void letter () {
}
public void word () {
}
}

You have defined a as an Arraylist. and are calling a.palindrome().
An Arraylist does not have the method palindrome(), I believe you just want to call palindrome() of your Test class.
To do this either:
Create an instance of Test within your main class then call palindrome() on that instance (preferred option)
or
make the method static then call Test.palindrome()
In either case you may want to consider having it take in argument of an Arraylist

What you need to do is Create an instance of your Test class
Test test = new Test();
Then call
test.palindrome();
Compiler fails because, since you called a.palindrome() and a being an instance of ArrayList<String>(), and it doesn't have a method ArrayList class doesn't have a method called palindrome()

Related

Scanner is requiring me to type inputs twice just for one to register

I've been doing a ton of research on this for the past few hours, with no luck. I am pretty sure this is a problem with .next() or .nextLine() (according to my searches). However, nothing has helped me solve my problem.
When I run the code below, I have to type in input twice, and only one of the inputs is subsequently added to the arrayList (which can be seen when you print the contents of the arrayList).
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
public class Tester{
public static void main(String[] args) {
AddStrings();
}
public static void AddStrings() {
Scanner console = new Scanner(System.in);
ArrayList<String> strings = new ArrayList<String>(); //this arraylist will hold the inputs the user types in in the while loop below
while(true) {
System.out.println("Input file name (no spaces) (type done to finish): ");
if(console.next().equals("done")) break;
//console.nextLine(); /*according to my observations, with every use of .next() or .nextLine(), I am required to type in the same input one more time
//* however, all my google/stackoverflow/ reddit searches said to include
//* a .nextLine() */
//String inputs = console.next(); //.next makes me type input twice, .nextLine only makes me do it once, but doesn't add anything to arrayList
strings.add(console.next());
}
System.out.println(strings); //for testing purposes
console.close();
}
}
Problem with your code is that you are doing console.next() two times.
1st Inside if condition and
2nd while adding to ArrayList.
Correct Code :
public class TestClass{
public static void main(String[] args) {
AddStrings();
}
public static void AddStrings() {
Scanner console = new Scanner(System.in);
ArrayList<String> strings = new ArrayList<String>(); //this arraylist will hold the inputs the user types in in the while loop below
while(true) {
System.out.println("Input file name (no spaces) (type done to finish): ");
String input = console.next();
if(input.equals("done")) break;
strings.add(input);
System.out.println(strings);
}
System.out.println(strings); //for testing purposes
console.close();
}
}
In your code, you are asking for two words to be inserted. Just remove one of them.
Use it this way:
String choice = console.next();
if (choince.equals('done')) break;
strings.add(choice);

How do I call a list from other classes? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Okay so I am building a program that will sort grades and records of students. It is a command-line program and when run it will start by asking for user input. there are several commands such as exit(exits program), load [file name](loads a file name), student [student name] (loads student records), etc. the others are not important. Well basically what I am wondering and what I am stuck on is all those functions will be in separate classes and will be called when the user inputs a specific command, but if I put the "load" command in its own class, then how do I get it to share its information with the other classes? I know I have to use BufferReader to read in the files, but how would I go implementing my load class, or if there is a better way feel free to say so. here is my code so far. there isn't much on my other classes because I feel like I need to figure out how to read in and share the file with the other classes first.
import java.util.*;
import java.io.*;
public class program7
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Grade Stats by ");
System.out.print(">");
while(scan.hasNextLine())
{
String input = scan.nextLine();
if(input.equals("exit"))
{
System.exit(0);
}
else if(input.equals("help"))
{
System.out.println("exit - program closes.");
System.out.println("load [filename] - loads a class database specified in [filename].");
System.out.println("students - prints out a list of students from the class, along ");
System.out.println(" with total points, and final grades for each student.");
System.out.println("assignments - prints out a list of assignments from the file, along with points possible");
System.out.println("student [student name] - Prints report for the student");
System.out.print(">");
}
else if(input.contains("load"))
{
String[] split = input.split(" ");
LoadStudents loadStudents = new LoadStudents(split[1]);
loadStudents.getFromFile();
System.out.print(">");
}
else if(input.equals("students"))
{
Students students = new Students();
students.printer();
System.out.print(">");
}
else if(input.equals("assignments"))
{
System.out.print(">");
}
else if(input.contains("student"))
{
String[] split = input.split(" ");
Student student = new Student(split[1]);
System.out.print(">");
}
else if(input.contains("assignment"))
{
}
else if(input.equals("grades"))
{
}
else
{
System.out.println("exit - program closes.");
System.out.println("load [filename] - loads a class database specified in [filename].");
System.out.println("students - prints out a list of students from the class, along ");
System.out.println(" with total points, and final grades for each student.");
System.out.println("assignments - prints out a list of assignments from the file, along with points possible");
System.out.println("student [student name] - Prints report for the student");
System.out.print(">");
}
}
}
}
That is my main class, but here is my Load and Students class.
import java.util.*;
import java.io.*;
public class LoadStudents
{
public String inputFile;
public List<Object> info = new ArrayList<Object>();
public LoadStudents(String inputFile)
{
this.inputFile = inputFile;
}
public List<Object> getFromFile()
{
try
{
BufferedReader in = new BufferedReader(new FileReader(inputFile));
try
{
String line = "";
while(in.readLine() != null)
{
line = in.readLine();
info.add(line);
}
}
catch(IOException e)
{
System.err.println("Exception, man");
}
finally
{
in.close();
}
}
catch(FileNotFoundException e)
{
System.err.println("File wasnt found ");
}
catch(IOException e)
{
System.err.println("Exception, man");
}
return info;
}
}
import java.util.*;
public class Students
{
public Students()
{
}
public void printer()
{
List<Object> info = (new LoadStudents()).getFromFile();
for (int x = 0; x<info.size(); x++)
{
System.out.println(info.get(x));
}
}
}
the Students class isnt finished but I am trying to figure out how to read the list from other classes. I have done research and have seen 3 similar problems, but they there is still something I'm missing because I keep getting the error
.\Students.java:11: error: constructor Load in class Load cannot be applied to g
iven types;
List<Object> info = (new LoadStudents()).getFromFile();
^
required: String
found: no arguments
reason: actual and formal argument lists differ in length
1 error
I understand it wants input, but I want it to use the previous input the user gives it when he inputs the command "input [whateverfile]".
Can anyone tell me how I can call that list my Load class produces to any other class?
There are many ways to do this. My suggestion is that your Load class should be a factory that actually creates a list of Student from the file, and not a list of strings.
Here are more suggestions:
Load class could have all methods statics and it could be non-instantiable. The fields you have in this class are useless after the file is read, you can just pass them to the static method as parameters.
Load is not a nice name for that class. LoadStudents is more meaningful, or even better StudentFactory.
Load and Student probably don't need to be public, package-private are be enough. Same for all the methods in these classes. Always use the lowest visibility possible.
data() is not a nice name for that method either. Something like getStudents(), or if you follow above advice, getFromFile(), is more meaningful.
Always print/log the stacktrace of the exceptions, otherwise you won't even know what/where it happened.
Instead of making the user type the whole commands, put a number on each option and let user select by number, that's faster to type and you avoid typo errors as well.
Only import the classes you're actually working with and not the whole package, that will make the compilation faster (unless you're importing a lot of classes from that package, which is not the case here).
EDIT: since you still don't understand what I mean, here's an example:
class StudentFactory {
private static List<Student> listCache = new ArrayList<>();
static List<Student> getStudents(final String filePath) {
if (listCache.isEmpty() {
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(filePath));
String line;
while((line = in.readLine()) != null) {
// Parse the line and create a Student instance from it, then add it to the list
listCache.add(student);
}
} catch(IOException e) {
System.err.println("Exception, man");
e.printStackTrace();
} catch(FileNotFoundException e) {
System.err.println("File wasnt found ");
e.printStackTrace();
} finally {
if (in != null) in.close();
}
}
return listCache;
}
private StudentFactory() {
// Avoid instantiation
}
}
Then you can just do
final List<Student> listOfStudents = StudentFactory.getStudents(filePath);
from anywhere in your code to get a list of students. filePath can be null if you already passed it previously.

Error with a Scanner variable in while loop [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I'm new in Java and I find it very complicated because of the errors that I come across with. So I have a problem with this piece of code:
Main Class:
public class Main {
public static void main(String[] args){
Answer a = new Answer();
String ans = null;
while(ans != "A"){
ans = a.create();
System.out.print(ans + "\n");
}
}
}
Answer class:
import java.util.Scanner;
public class Answer {
public String create(){
Scanner s = new Scanner(System.in);
return s.next();
}
}
I want the program to allow me to write something. Then, if what I've written hasn't been the letter A, the program must allow me to write something else, otherwise has to stop. But, even though I write "A", the program is still keeping on, allowing me to write something else. What's wrong with the code?
String can't be compared properly using the != operator. Instead you should use while(!ans.equals("A")). Secondly, try not to recreate the Scanner object in the create method. This is a resource waste.

Cannot make static reference to the non-static method printMenuGetSelection() from the type SpecialAssignment1 [duplicate]

This question already has answers here:
Cannot make a static reference to the non-static method
(8 answers)
Closed 8 years ago.
Pre Edit: The problem is when I mark it as static, so
public static int printMenuGetSelection()
it gives me the message
This Static method cannot hide the instance method from AMenu
I'm writing a Java program that reads files and gives the user multiple options for displaying things about the file. I'm currently writing a menu interface that implements an actual Interface and makes the program easier to use. However, I'm getting an exception when I try to call the menu method in my main method. The error is on the one active line in the main method where I call printMenuGetSelection(), and it says
Cannot make static reference to the non-static method printMenuGetSelection() from the type SpecialAssignment1
How do I fix this bug? here is my program:
import java.util.*;
import java.io.*;
import java.text.*;
public class SpecialAssignment1 implements AMenu {
public static void main(String[] args) throws FileNotFoundException{
printMenuGetSelection();
/*System.out.println(RewardCustomer("transactions1.dat")); //CURRENTLY DISPLAYING TOP 6, DOESN'T WORK WITH TIES OR TOPN < lines
ProcessTransactionsFile("transactions2.dat", 52);*/
}
public int printMenuGetSelection() throws FileNotFoundException{
boolean runProgram = true;
Scanner s = new Scanner(System.in);
printStartMenu();
String startMenuSelection = s.next();
while(runProgram){
if(startMenuSelection.equals("1")){
startMenu1();
} else if(startMenuSelection.equals("2")){
startMenu2();
} else if(startMenuSelection.equals("3")){
startMenu3();
} else if(startMenuSelection.equals("4")){
startMenu4();
} else if(startMenuSelection.equals("5")){
runProgram = false;
} else {
System.out.println("***Selection Invalid!***");
}
}
return 1;
}
public static void printStartMenu(){
System.out.println("**********************************************************");
System.out.println("Main Menu...");
System.out.println(" (1) RewardCustomers");
System.out.println(" (2) ProcessTransactionFiles");
System.out.println(" (3) TopCustomers");
System.out.println(" (4) QueryStatsFile");
System.out.println(" (5) Quit");
System.out.println(" Enter a valid selection: ");
}
public static void startMenu1() throws FileNotFoundException{
boolean runMenu1 = true;
while(runMenu1){
Scanner s = new Scanner(System.in);
System.out.println("Reward Customers Menu...");
System.out.println(" (1) Use transactions1.dat");
System.out.println(" (2) Use transactions2.dat");
System.out.println(" (3) Quit");
System.out.println(" Enter a valid selection: ");
String menu1Selection = s.next();
if(menu1Selection.equals("1")){
System.out.println(RewardCustomer("transactions1.dat"));
} else if(menu1Selection.equals("2")){
System.out.println(RewardCustomer("transactions2.dat"));
} else if(menu1Selection.equals("3")){
runMenu1 = false;
} else {
System.out.println("***Selection Invalid!***");
}
}
}
public static void startMenu2(){
boolean runMenu2 = true;
while(runMenu2){
Scanner s = new Scanner(System.in);
System.out.println("Process Transaction Files Menu...");
System.out.println(" (1) Create transactions2.dat file");
System.out.println(" (2) Display transactions1.dat");
System.out.println(" (3) Display transactions2.dat");
System.out.println(" (4) Query transactions1.dat");
System.out.println(" (5) Query transactions2.dat");
System.out.println(" (6) Quit");
System.out.println(" Enter a valid selection: 4");
String menu2Selection = s.next();
if(menu2Selection.equals("1")){
}
}
}
public static void startMenu3(){
}
public static void startMenu4(){
}
I removed the code not pertaining to the question to make it easier to read, if it's needed I'll put it in. Also, here is the AMenu Interface. Please do not suggest any other changes to my program. If you think it's dumb to have the menu as an Implemented Interface, I 100% agree with you but that's the requirement. For reference, here is the AMenu Interface:
import java.io.FileNotFoundException;
public interface AMenu {
/**
* Prints a menu with selections and logic to return a valid selection.
* #return the selected item
*/
abstract int printMenuGetSelection() throws FileNotFoundException;
/**
* #return the numberOfMenuItems
*/
abstract int getNumberOfMenuItems();
}
Since printMenuGetSelection() is non static, you cannot call it from within the static method main() unless you create an instance of SpecialAssignment1 and call the method on that object.
you need to create an instance of your SpecialAssignment1 then call the method from that, as abstract requires an object.
As other people have said, you need to create an instance of SpecialAssignment1, then call printMenuSelection() on it. Part of what's making this confusing though is that you've stuck the main method inside the menu interface class. This whole thing would make more sense if you had a class SpecialAssignment1 with just the main method and a separate MenuGenerator class with all the menu generation stuff.

How can I randomly call a method to run in java?

I am writing a program that will generate a geometry Logic Word Problem, and I am having trouble with it. My goal is to have the program randomly create a word problem that is pre-designed. So far, the program takes input from the user, and then uses that information in the Story methods, somewhat like a game of Mad Libs. Anyways, I want to randomly chose a Story method to run each time the user starts the program. So far this is what I have:
import cs1.Keyboard;
public class LogicProof {
//Main method
public void main () {
System.out.println ("Enter 1. to start.");
System.out.println ("Enter 2. to exit.");
int choice = Keyboard.readInt();
if (choice == 1) { //Take info in and send to createStory
//Randomly run methods
}
if (choice == 2) {
System.out.println ("\nGoodbye.");
}
//Create the first story using inputs from main
private void createStory(String adj,String adj2,String adj3,String action) {
//Use values from main() to create a problem
}
There are two other createStory methods as well. Also, I am going to display the proofs of each problem, and each method has its own proof, so would I be able to then display the proof for the same method, basically just link together the proof method, and story method?
I'm fairly new to Java, and appreciate the help.
Thanks in advance.
To only answer your title, you could use random generation with reflection, but that is in no way how you should solve your current problem.
Don't try and randomly invoke methods. Take a look at java.util.Random's nextInt() and use that to do unique operations based on the value it returns.
This seems like Homework which is why I'm not giving you a full solution here.
public class MadLibs {
public static final String[] STARTERS = { /* ... */ };
public static final String[] ENDINGS = { /* ... */ };
public static String generate(String ... adjectives) {
final Random random = new Random();
final StringBuilder string = new StringBuilder(STARTERS[random.nextInt(STARTERS.length-1)]);
for (String adjective : adjectives) {
string.append(adjective);
string.append(TRANSITIONS[random.nextInt(TRANSITIONS.length - 1)]);
}
return string.toString();
}
}
That's an extremely simple and rough implementation to get you started.
Or maybe, if you have only a few concrete variations:
public class MadLibs {
public static String generate(String ... adjectives) {
int result = new Random().nextInt(MAX);
String madLib = null;
switch (result) {
case 0:
// ...
break;
case 1:
// ...
break;
default:
// ...
break;
}
return madLib;
}
}
Like said above, use random number generation to yourself a 1,2,3,4 ect... Then pass that number into your method as a parameter and then use "if, if else" statements to choose the correct operation to perform. Again, like stated above I will not give any code in case this is indeed a homework problem.
You could generate a Word or Phrase object, populate them into a List.
From there us something like Random or Math.random to pull a word or phrase from the list

Categories

Resources