This code doesn't seem to compile cleanly - java

I am creating a program in Java for a restaurant. I am using ArrayList but for some reason my starter class doesn't seem to run in the main menu.
This is my starter class:
import java.util.ArrayList;
public class Starter
{
Starter()
{
String[] myList = {"Coffee", "Tea", "Somosas", "Cake"};
//System.out.println(myList[]);
}
}
This seems to be correct, but when I try to choose from the Main menu it doesn't seem to work.
Main Menu:
import java.util.Scanner;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Menu
{
static Scanner input = new Scanner(System.in);
public static void main(String[]args)
{
System.out.println("1=Starter");
System.out.println("2= Main Course");
System.out.println("3=Desert");
int a =input.nextInt();
input.nextLine();
if(a==1)
{
System.out.println("Starter");
Starter OS1=new Starter();
System.out.println("Your starter is "+OS1.myList[]);
}
else if(a==2)
{
System.out.println("Main Course");
MaiinCourse OMC1=new MaiinCourse();
System.out.println("Your MainCourse is "+OMC1.MCname);
System.out.println("The price is "+OMC1.MCprice);
}
else if(a==3)
{
System.out.println("Desert");
Deserrt ODS1=new Deserrt();
System.out.println("Your Desert is "+ODS1.DSname);
System.out.println("The price is "+ODS1.DSprice);
}
else
{
System.out.println("End");
System.out.println("Program Closing");
System.exit(1);
}
}
}
The error I get is:
'.class' expected System.out.println("Your starter is "+OS1.myList[]);
How to fix this?
When I run the main menu it should allow me to choose from the array list.

I did few changes to your code. Now it works. Try and see.
import java.util.Arrays;
import java.util.Scanner;
public class Menu
{
static Scanner input = new Scanner(System.in);
public static void main(String[]args)
{
System.out.println("1=Starter");
System.out.println("2= Main Course");
System.out.println("3=Desert");
int a = input.nextInt();
input.nextLine();
if (a == 1)
{
System.out.println("Starter");
Starter OS1 = new Starter();
System.out.println("Your starter is " + Arrays.toString(OS1.getMyList()));
}
}
}
class Starter
{
private String[] myList = {"Coffee", "Tea", "Somosas", "Cake"};
public String[] getMyList()
{
return myList;
}
}

Your code won't work because you are trying to give an Array values within you class constructor (Starter constructor in this case). This will lead to a RunTime exception because you cannot create Array constants within a constructor. I much more viable approach would be to create a private Array as an attribute for each object that you create of type "Starter". Then you can use something that we call a "Getter" method to get the value of the myList attribute for the instance you're creating. Here's a mini example of how we can change your Starter class structure below:
public class Starter {
private String[] myList = {"Coffee", "Tea", "Somola", "Cake"};
public String[] getterMethod() {
return this.myList;
}
}
Now we have what is called a "Getter" method in Java which will return the private class attribute so that users cannot alter the internal state of the Object. Here is an example of how you will call the Array in your main method:
public class App {
public static void main( String[] args ) throws IOException{
System.out.println("1=Starter");
Scanner input = new Scanner(System.in);
System.out.println("Enter a number");
int a = input.nextInt();
if(a == 1) {
System.out.println("Starter");
Starter OS1 = new Starter();
System.out.println(Arrays.toString(OS1.getterMethod()));
}
}
}
That is a very simplified version of your code that I simply used to illustrate the broader concept. Here is the output:
1=Starter
Enter a number
1
Starter
[Coffee, Tea, Somola, Cake]
We simply call the getterMethod() which will return the value for the private Array that you are looking for.

Actually, your myArray is not visible outside the Starter class, so you have to make it visible by declaring as public, or package default. Here you can take help of Arraylist.
So you can change your class as below :
public class Starter {
// this myList will be visible outside of this class and can be accessed to show menu.
ArrayList<String> myList = new ArrayList<>();
Starter() {
String[] myArray = { "Coffee", "Tea", "Somosas", "Cake" };
for (String str : myArray) {
myList.add(str);
}
//System.out.println(myList);
}
}
and kindly update Your Menu.java class as below :
import java.util.Scanner;
public class Menu {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("1=Starter");
System.out.println("2= Main Course");
System.out.println("3=Desert");
int a = input.nextInt();
input.nextLine();
if (a == 1) {
System.out.println("Starter : ");
Starter os1 = new Starter();
for (String str : os1.myList) {
System.out.print(str + " ");
}
}
}
}

Related

MVC Random Word Generator

So I am creating an MVC Random Word generator that submits user input and retrieves it. I am having a hard time with my RandomWordModel class. I created an ArrayList of strings that are supposed to store user input and then retrieve it one the user presses the "Retrieve Word" button.
public class RandomWordModel {
private ArrayList<String> randomWords;
public RandomWordModel()
{
}
public String putWord(String userWords) {
randomWords.add(userWords);
return userWords;
}
public String getWord() {
Collections.shuffle(randomWords);
String userInput = randomWords.get(randomWords.size());
return userInput;
}
This is what I have so far and it is not really working for some reason. I'm not sure if I am doing this wrong but if anyone could help that would be great.
First of all you forget to initialize the arraylist. Try to initialize ArrayList as :
List<String> randomWords= new ArrayList<String>();
The working snippet is :
private ArrayList<String> randomWords = new ArrayList<String>();;
public static void main(String args[]) {
rep1 obj = new rep1();
obj.putWord("user1");
obj.putWord("user2");
obj.putWord("user3");
System.out.println(obj.randomWords);
Object[] object = obj.getWord();
System.out.println(Arrays.toString(object));
}
public void RandomWordModel() {
}
public String putWord(String userWords) {
randomWords.add(userWords);
return userWords;
}
public Object[] getWord() {
Collections.shuffle(randomWords);
return randomWords.toArray();
}
I'm not sure why you would want to create a full MVC model for that.
I would personally go with something simpler like below:
import java.util.Scanner;
import java.util.Random;
public class test2{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
Random rand = new Random();
System.out.print("Enter string > ");
String input = sc.nextLine();
String words[] = new String[input.length()];
if(!input.isBlank())
words = input.split(" ");
System.out.println(words[rand.nextInt(words.length)]);
}
}
[Edited Code Below]
As per your requirement you can split the above code into MVC rather easily. It is very much just rearranging the codes.
RandomWordView.java
import java.util.Scanner;
public class RandomWordView{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print("Enter string > ");
String input = sc.nextLine();
RandomWordModel rwm;
if(!input.isBlank()){
rwm = new RandomWordModel(input.split(" "));
System.out.println(RandomWordController.getRandomWord(rwm));
}
}
}
RandomWordModel.java
public class RandomWordModel{
String wordArr[];
public RandomWordModel(String wordArr[]){
this.wordArr = wordArr;
}
public String[] getWordArr(){
return this.wordArr;
}
}
RandomWordController.java
import java.util.Random;
public class RandomWordController{
public static String getRandomWord(RandomWordModel x){
Random rand = new Random();
String wordArr[] = x.getWordArr();
return wordArr[rand.nextInt(wordArr.length)];
}
}
As the functionality requirement you provided is rather simple there is really no need for an MVC framework as you can see. The model for your question is simply a String array and the controller only requires a single function of random word which is why my initial recommendation for going simple. Hope this helps you see how it can be converted to MVC nonetheless.

How to effectively generate object in for or while

I have this kind of structure of program.
This program have one function named run(), and the other function named solve().
In this program, I want to get some information from run() and solve().
Also, I want to put these information to one list vector (named information_one_iteration in the following code).
Because this vectors get together to form a matrix (named information in the following code).
That's why I define the information_one_iteration as static variable, and in every new iteration new objects is defined newly.
But, I know this kind of way is not effective!
How can I improve it?
package java_test2;
import java.util.ArrayList;
import java.util.ArrayList;
import java.util.Random;
public class staticvarTest {
private Random random = new Random();
static ArrayList<ArrayList<String>> information = new ArrayList<ArrayList<String>>();
static ArrayList<String> information_one_iteration = new ArrayList<String>();
public staticvarTest() {
}
public void run() {
for (int i=0; i<10; i++) {
information_one_iteration.add(String.valueOf(i));
solve(); // add two random number generated in function solve()
information.add(information_one_iteration);
information_one_iteration = new ArrayList<String>();
}
print_information(information);
}
public void solve() {
information_one_iteration.add(String.valueOf(random.nextInt()));
information_one_iteration.add(String.valueOf(random.nextInt()));
}
public static void print_information(ArrayList<ArrayList<String>> information) {
for (ArrayList<String> newLine : information) {
ArrayList<String> list_set = newLine;
System.out.println("");
for(String data: list_set) {
System.out.print(data+" ");
}
System.out.println("");
}
System.out.println("");
}
public static void main(String args[]) {
staticvarTest na = new staticvarTest();
na.run();
}
}
Since you are not using static ArrayList<String> information_one_iteration = new ArrayList<String>(); anywhere apart from the run method you can remove it.
I have changed the random variable since it's okay for multiple objects to share it - the behaviour remains the same therefore no need to initialize every time Main object is created.
Change the solve method to take a ArrayList as a parameter too.
print_information looks okay but there is no need for ArrayList<String> list_set = newLine;
I have also made information as a state variable over a static variable so that each instance of the object can have it's own information therefore allowing you to run multiple instances of this class.
I also added a lambda to print the members to give you an idea about them newLine.forEach(data -> System.out.println(data + " "));.
Finally I have used variable names and class names that adhere to Java coding conventions for better readability. Here is one of the style guides which you may follow https://google.github.io/styleguide/javaguide.html
The cleaned up version of your code is below
package com.company;
import java.util.ArrayList;
import java.util.Random;
public class Main {
private static Random random = new Random();
private ArrayList<ArrayList<String>> information = new ArrayList<>();
private void run() {
for (int i=0; i<10; i++) {
ArrayList<String> informationInIteration = new ArrayList<>();
informationInIteration.add(String.valueOf(i));
solve(informationInIteration); // add two random number generated in function solve()
information.add(informationInIteration);
}
printInformation();
}
private void solve(ArrayList<String> iterationInformation) {
iterationInformation.add(String.valueOf(random.nextInt()));
iterationInformation.add(String.valueOf(random.nextInt()));
}
private void printInformation() {
for (ArrayList<String> newLine : information) {
System.out.println();
newLine.forEach(data -> System.out.println(data + " "));
System.out.println();
}
System.out.println();
}
public static void main(String[] args) {
Main main = new Main();
main.run();
}
}
Based on your comments I am adding a method that creates no object for storing any information.
package com.company;
import java.util.Random;
public class Main {
private Random random = new Random();
private void run() {
for (int i=0; i<10; i++) {
System.out.println(String.valueOf(i));
System.out.println(random.nextInt() + " " + random.nextInt() + "\n");
}
}
public static void main(String[] args) {
Main main = new Main();
main.run();
}
}
This should work for you.
public void run() {
for (int i=0; i<10; i++) {
staticvarTest.information.add(solve(String.valueOf(i)));
}
print_information(information);
}
public String[] solve(String i) {
return {String.valueOf(random.nextInt()),
String.valueOf(random.nextInt()),
i};
}
Or you could maybe concatenate the array returned in solve() and the i String and avoid passing the variable around.
I have not tested the code above btw but apart from accessing and modifying the static variable there shouldn't be a problem.
Hope this works for you.

ArrayList class separate from Java main file

I have two separate files, one named WonderfulArrayList, and the other named ArrayListMain (I'm experimenting with ArrayLists, and I'm not quite sure what to do) and so I have a method in the WonderfulArrayList file, but the main file cannot see the method, which I have named booladdData, which would return true once the data is added to the array list. My WonderfulArrayList file is the following:
import java.util.*;
import java.io.*;
public class WonderfulArrayList{ //implement WonderfulArrayList
public static int ADDNums;
public static int index;
public static int HEADNums;
public static ArrayList<Integer> arr = new ArrayList<Integer>(15);
public static boolean booladdData(ArrayList<Integer>arr){
arr.add(ADDNums);
return true;
}
}
As you can see, I have booladdData instantiated with the ArrayList, named arr. Now, if you look at my main file:
public class ArrayListMain{
//public ArrayList<Integer> arr = new ArrayList<Integer>(15);
public static void main(String[]args){
ArrayList<Integer> arr = new ArrayList<Integer>(15);
int MenuNum = 0;
int ADDNums = 0;
Object Obj = new Object();
Scanner scanner1 = new Scanner(System.in); //set up scanner for user input
while(MenuNum != 7){ //menu loop
Menu(MenuNum);
MenuNum = scanner1.nextInt();
if(MenuNum == 1){
arr.booladdData();
}
For some reason, even though I know that booladdData is created as public and they're both in the same folder, the main file doesn't have the scope to be able to see booladdData in the separate file.
Any idea what I'm doing wrong?
You should be calling WonderfulArrayList.booladdData(arr) instead of arr.booladdData(). The method booladdData() is defined as a class method of your WonderfulArrayList class. It's not an instance method of Java's ArrayList.
You also might want to read into object-oriented programming. Everything in your code is static.
You need to create your type instead of ArrayList
package com.jbirdvegas.test;
import java.util.ArrayList;
public class MainClazz {
public static void main(String[] args) {
// notice I'm creating my type `MyArrayList` instead of `ArrayList` type
MyArrayList myArrayList = new MyArrayList();
myArrayList.add("blah");
System.out.println("My message:" + myArrayList.getSomething());
}
}
class MyArrayList extends ArrayList {
public String getSomething() {
return "something";
}
}
Prints:
My message: something

arraylist in java to sort data [duplicate]

This question already has answers here:
Collections.sort with multiple fields
(15 answers)
Closed 7 years ago.
so i'm having issues making this work for me. what this code needs to do is have 3 different (string) fields that then sort them into alphabetical order i've had help before but it wont run on my netbeans. i am currently up to date with all updates as well.
heres the code i have so far
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
import java.util.Comparator;
public class test {
private Scanner scan = new Scanner(System.in);
private List<LayoutOfScientist> scientistsNames = new ArrayList<LayoutOfScientist>();
private String name, field, idea;
private boolean continueLoop = true;
private int countTo3 = 0;
private void run() {
while(countTo3<3&&continueLoop) {
if(countTo3>0) {
System.out.println("Would you like to add another scientist? (Y/N)");
}
if(countTo3 == 0 || scan.nextLine().equalsIgnoreCase("y")) {
System.out.println("Please enter the scientist's name:");
name = scan.nextLine();
System.out.println("Please enter the scientist's field:");
field = scan.nextLine();
System.out.println("Please enter the scientist's idea:");
idea = scan.nextLine();
scientistsNames.add(new LayoutOfScientist(name, field, idea));
} else {
continueLoop = false;
}
countTo3++;
}
scientistsNames.sort(Comparator.comparing(LayoutOfScientist::getScientistName));
for(LayoutOfScientist lOS : scientistsNames) {
System.out.println(lOS.getScientistName() + ", " + lOS.getScientistField() + ", " + lOS.getScientistIdea());
}
}
private class LayoutOfScientist {
private String scientistName, scientistField, scientistIdea;
private LayoutOfScientist(String scientistName, String scientistField, String scientistIdea) {
this.scientistName = scientistName;
this.scientistField = scientistField;
this.scientistIdea = scientistIdea;
}
public String getScientistName() {
return scientistName;
}
public String getScientistField() {
return scientistField;
}
public String getScientistIdea() {
return scientistIdea;
}
}
public static void main(String[] args) {
new Test().run();
}
}
Your class name is test (lowercase t) and in your main method, you are calling Test().run().
You need to rename your class to be Test and that should work. Or if your file is test you need to change Test().run() to test().run() instead of public class test to public class test. However, it is good programming practice to name a ClassLikeThis.
If your error is something else entirely, tell us what the error is.

Passing data to a method

I am trying to pass "personListToPrint" to main.java and have it come up when switch 3 is used, however it will not work. I am not sure how to go about fixing this. Any ideas??
here is main.java
package hartman;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Printer.printWelcome();
Scanner keyboard = new Scanner(System.in);
ArrayList<Person> personList = new ArrayList<>();
boolean keepRunning = true;
while (keepRunning) {
Printer.printMenu();
Printer.printPrompt("Please enter your operation: ");
String userSelection = keyboard.nextLine();
switch (userSelection) {
case "1":
Database.addPerson(personList);
break;
case "2":
Database.printDatabase(personList);
break;
case "3":
Printer.printSearchPersonTitle();
String searchFor = keyboard.nextLine();
Database.findPerson(searchFor);
Printer.printPersonList(personListToPrint);
break;
case "4":
keepRunning = false;
break;
default:
break;
}
}
Printer.printGoodBye();
keyboard.close();
}
}
and here is database.java
package hartman;
import java.util.ArrayList;
import java.util.Scanner;
public class Database {
static Scanner keyboard = new Scanner(System.in);
private static ArrayList<Person> personList = new ArrayList<Person>();
public Database() {
}
public static void addPerson(ArrayList<Person> personList) {
Printer.printAddPersonTitle();
Printer.printPrompt(" Enter first name: ");
String addFirstName = keyboard.nextLine();
Printer.printPrompt(" Enter last Name: ");
String addLastName = keyboard.nextLine();
Printer.printPrompt(" Enter social Security Number: ");
String addSocial = keyboard.nextLine();
Printer.printPrompt(" Enter year of birth: ");
int addYearBorn = Integer.parseInt(keyboard.nextLine());
System.out.printf("\n%s, %s saved!\n", addFirstName, addLastName);
Person person = new Person();
person.setFirstName(addFirstName);
person.setLastName(addLastName);
person.setSocialSecurityNumber(addSocial);
person.setYearBorn(addYearBorn);
personList.add(person);
}
public static void printDatabase(ArrayList<Person> personList) {
System.out
.printf("\nLast Name First Name Social Security Number Age\n");
System.out
.printf("=================== =================== ====================== ===\n");
for (Person p : personList) {
System.out.printf("%-20s%-21s%-24s%s\n", p.getLastName(),
p.getLastName(), p.getSocialSecurityNumber(), p.getAge());
}
}
public static ArrayList<Person> findPerson(String searchFor) {
ArrayList<Person> matches = new ArrayList<>();
for (Person p : personList) {
boolean isAMatch = false;
if (p.getFirstName().equalsIgnoreCase(searchFor)) {
isAMatch = true;
}
if (p.getLastName().equalsIgnoreCase(searchFor)) {
isAMatch = true;
}
if (p.getSocialSecurityNumber().contains(searchFor)) {
isAMatch = true;
;
} else if (String.format("%d", p.getAge()).equals(searchFor))
if (isAMatch) {
}
matches.add(p);
Printer.printPersonList(matches);
}
return matches;
}
}
and last, here is printer.java
package hartman;
import java.util.ArrayList;
public class Printer {
public static void printWelcome() {
System.out.printf("WELCOME TO PERSON DATABASE!\n");
}
public static void printGoodBye() {
System.out.printf("\nGOOD BYE!!\n");
}
public static void printMenu() {
System.out.printf("\nMain Menu\n");
System.out.printf("---------\n\n");
System.out.printf(" 1. Add a new Person to the database.\n");
System.out.printf(" 2. Print the database.\n");
System.out.printf(" 3. Search for a person in the database.\n");
System.out.printf(" 4. Exit the application.\n");
System.out.printf("\n");
}
public static void printPrintMenu() {
System.out.printf("Print\n\n");
}
public static void printAddPersonTitle() {
System.out.printf("\nAdd Person to Database\n\n");
}
public static void printPrompt(String promptForWhat) {
System.out.printf("%s", promptForWhat);
}
public static void printPersonSaved(Person personSaved) {
System.out.printf("%s", personSaved);
}
public static void printSearchPersonTitle() {
System.out.printf("\nSearch for Person in Database\n\n");
System.out.printf("Enter search value: ");
}
public static void printPersonList(ArrayList<Person> personListToPrint) {
System.out
.printf("\nLast Name First Name Social Security Number Age\n");
System.out
.printf("=================== =================== ====================== ===\n");
for (Person p : personListToPrint) {
System.out.printf("%-20s%-21s%-24s%s\n", p.getLastName(),
p.getLastName(), p.getSocialSecurityNumber(), p.getAge());
}
}
}
You did not define variable
personListToPrint
Replace case 3 with next
case "3":
Printer.printSearchPersonTitle();
String searchFor = keyboard.nextLine();
ArrayList<Person> personListToPrint = Database.findPerson(searchFor);
Printer.printPersonList(personListToPrint);
break;
Now is compilable
Printer.printPersonList(personListToPrint);
Where is it supposed to come from? personListToPrint is never defined anywhere. (I Ctrl-F searched your code samples and it's nowhere)
your calling printer directly without having created an object of the class.
Printer printerObj = new Printer();
I think I have your confusion figured out, but explaining it is a tad tricky.
In your Printer class, you have the following method declaration:
public static void printPersonList(ArrayList<Person> personListToPrint)
In this case, personListToPrint is the name of the variable you'll use INSIDE this method to refer to the ACTUAL ArrayList that is passed to the method when it's called from the external source.
In your case, you are calling it using this invocation within your Case "3" block:
Printer.printPersonList(personListToPrint);
Even though the method calls it "personListToPrint," when you make the above call, you really want to pass in personList. Within Main, personList refers to some ArrayList, let's say at some memory location defined as "0100." When Printer.printPersonList is invoked, you want to pass in the array list you want printed, in this case personList (residing at memory "0100"). Once inside of printPersonList, the ArrayList stored at "0100" will be referred to using the variable name personListToPrint. It's two different names for the same memory location.
The other person who commented about the fact that you never declared or instantiated personListToPrint is right, so when you call printPersonList(personListToPrint) the way you are doing now, you're passing in a null since that particular variable was never declared or instantiated (you should actually get a compile error).
If this is confusing, comment back and I'll try to explain in a different way.

Categories

Resources