I don't understand why but my method can't access the arraylist. When I try to add from input it says error: cannot find symbol.
public class Kitchen{
public static void Kitchen(String[] args ){
ArrayList<String> Utensil = new ArrayList<String>();
Utensil.add("Knife");
Utensil.add("Boiler");
System.out.println(Utensil);
}
public void addUtensil(){
Scanner sc = new Scanner(System.in);
System.out.println("Utensil to add? ");
String new = sc.nextLine();
Utensilio.add(new);
}
}
You have to pass the Utensil ArrayList as a parameter to the addUtensil() method.
public static void Kitchen(String[] args ){
ArrayList<String> Utensil = new ArrayList<String>();
Utensil.add("Knife");
Utensil.add("Boiler");
addUtensil(Utensil);
System.out.println(Utensil);
}
public static void addUtensil(List<String> Utensil){
Scanner sc = new Scanner(System.in);
System.out.println("Utensil to add? ");
String new = sc.nextLine();
Utensilio.add(new);
}
There are two different methods
Kitchen
addUtensil
you declared a below local variable in one method(Kitchen) and trying to access on other method(addUtensil).
ArrayList<String> Utensil = new ArrayList<String>();
In java you can not access the local variable of one method to another
Another option is to define it as an class variable, remember that we can access a static variable via not static method,but on the other side it's not
public class Kitchen{
private static ArrayList<String> Utensil = new ArrayList<String>();
public static void Kitchen(String[] args ){
Utensil.add("Knife");
Utensil.add("Boiler");
System.out.println(Utensil);
}
public void addUtensil(){
Scanner sc = new Scanner(System.in);
System.out.println("Utensil to add? ");
String new = sc.nextLine();
Utensilio.add(new);
}
}
Related
This point of this program is to limit the character length of a username to 20 characters. It is one part of a larger program which currently only contains a Main method. In the interest of cleaning and clarifying my code, I would like to separate the various functions into distinct methods.
Currently, I'm trying to set class variables so that they can be used in multiple methods. This is what I have so far:
public class Program
{
Scanner read = new Scanner(System.in);
String firstName = read.nextLine();
String lastName = read.nextLine();
public void main(String[] args) {
domainCharLimit();
}
public void domainCharLimit() {
String firstNameNew = firstName.replace("'", "");
String lastNameNew = lastName.replace("'", "");
String domainUsername = firstNameNew + "." + lastNameNew;
if (domainUsername.length()>20) {
String cutName = domainUsername.substring(0, 20);
domainUsername = cutName;
}
System.out.print(domainUsername);
}
}
I have tried setting one or both methods to static, which did not resolve the issue. In this state, when run, the program will not return an errors but rather give "no output"
Main method has to be static! It is entry to your program and its signature has to be like that.
In order to call non static method inside it you need to instantiate an object and call it on that object. In your case something like
public static void main(String[] args) {
Program p = new Program();
p.domainCharLimit();
}
First: Main Method should be always static.
Second: Because you are calling domainChatLimit() from Main(static) than it should be also static
Third: Because you used firstName, lastName attributes in a static method domainChatLimit() then they should be also static
Fourth: Scanner should be also static because you are using it to get firstName, lastName and they are both static.
NOTE: There is no need to define a new instance of this class to call an internal method
Solution should be like below (tested successfully):
import java.util.Scanner;
public class Program{
// variables below should be defined as static because they are used in static method
static Scanner read = new Scanner(System.in);
static String firstName = read.nextLine();
static String lastName = read.nextLine();
// Main method is static
public static void main(String[] args) {
//There is no need to define a new instance of this class to call an internal method
domainCharLimit();
}
// calling from main static method so it should be static
public static void domainCharLimit() {
String firstNameNew = firstName.replace("'", "");
String lastNameNew = lastName.replace("'", "");
String domainUsername = firstNameNew + "." + lastNameNew;
if (domainUsername.length()>20) {
String cutName = domainUsername.substring(0, 20);
domainUsername = cutName;
}
System.out.print(domainUsername);
}
}
if you want to create a Generic Util for that functionality you can do below logic:
PogramUtil.java
import java.util.Scanner;
public class ProgramUtil {
Scanner read = new Scanner(System.in);
String firstName = read.nextLine();
String lastName = read.nextLine();
public void domainCharLimit() {
String firstNameNew = firstName.replace("'", "");
String lastNameNew = lastName.replace("'", "");
String domainUsername = firstNameNew + "." + lastNameNew;
if (domainUsername.length()>20) {
String cutName = domainUsername.substring(0, 20);
domainUsername = cutName;
}
System.out.print(domainUsername);
}
}
now you can call this way :
Program.java
public class Program{
// Main method is static
public static void main(String[] args) {
ProgramUtil programUtil = new ProgramUtil();
programUtil.domainCharLimit();
}
}
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.
EDIT: I understand what the issue is now. I was creating a new instance of the class which reset the values of the variables inside of it. For anyone wondering you can use 'static' for the value of a variable to stay the same throughout all instance of the class
Example: public static int example = 10;
I am trying to add a string to a text file, however when I add the string it puts "null" in the file instead of my string. The string is "listName"
Class where my a value is set to the string:
public class NewList {
private String listName;
public void newList() {
System.out.println("NEW LIST");
System.out.print("List Name: ");
#SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
setListName(scanner.next());
System.out.println(listName);
ListsWriter listsWriterObject = new ListsWriter();
listsWriterObject.listsWriter();
}
public String getListName() {
return listName;
}
public void setListName(String listName) {
this.listName = listName;
}
Class where the string is added to the text file:
public class ListsWriter {
public void listsWriter() {
NewList newListObject = new NewList();
File lists = new File("lists.txt");
try{
PrintWriter pw = new PrintWriter(new FileWriter(lists, true));
pw.append(newListObject.getListName() + "\n");
pw.close();
}catch(IOException ex){
ex.printStackTrace();
}
}
}
Take a look at the order how your code is executed. You start with your scanner stuff and save the name inside the variable private String listName;. This variable belongs to the instance of the class NewList you are currently in. It is important to note that if you create other instances of NewList then they will all have their own listName variables.
Next you create ListsWriter and call its method. There you try to read the list name with newListObject.getListName() however you use NewList newListObject = new NewList(); before. This will create a new instance of NewList. It has its own listName variable, it is not the same than the variable of the other instance! Thus it is null.
If you want the name of the other instance you need to pass either the value or a reference to this instance to the ListsWriter object.
You can do this by using a constructor for ListsWriter that accepts a String as parameter (or a reference to a NewList object). Or you add the parameter to the method listsWriter.
For example:
public void listsWriter(String listName) {
Okay! so I have modified your code you can use it :)
NewList.java
public class NewList {
private String listName;
public void newList() {
System.out.println("NEW LIST");
System.out.print("List Name: ");
#SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
listName = scanner.next();
System.out.println(listName);
ListsWriter listsWriterObject = new ListsWriter();
listsWriterObject.listsWriter(listName);
}
public static void main(String[] args) {
new NewList().newList();
}
}
ListsWriter.java
public class ListsWriter {
public void listsWriter(String listName) {
File lists = new File("lists.txt");
try{
PrintWriter pw = new PrintWriter(new FileWriter(lists, true));
pw.append(listName + "\n");
pw.close();
}catch(IOException ex){
ex.printStackTrace();
}
}
}
I am trying to get the value of a method that is inside a class into the main class.
The code is supposed to let me give the variables 'a', 's' and 'u' each a value by using the console and afterwards return the values to the main class.
import java.util.*;
public class Auslesen
{
String a;
private int s;
double u;
public class Scannen
{
Scanner scanner = new Scanner(System.in);
public int Methode()
{
s = scanner.nextInt();
return s;
}
}
}
and here is my main class:
public class Start
{
public static void main(String[] args)
{
Auslesen auslesen = new Auslesen();
//System.out.println(auslesen);
Auslesen.Scannen scannen = auslesen.new Scannen();
//System.out.println(scannen);
Auslesen.Scannen.Methode methode = scannen.new Methode();
System.out.println(methode);
//my approach which didnt worked out...
}
}
Methode is a method not a class. You don't create it with new or create it at all for that matter. A method is defined in a class and you just call it. E.g.
System.out.println(scannen.Methode());
and delete this line :
Auslesen.Scannen.Methode methode = scannen.new Methode();
Also try to stick to the Java naming convention : class names start with uppercase method and variable names with lowercase.
First of all why are you declaring a class inside another class ? If you simply want to return a value from one class to another class then you can do something like this -
String a;
private int s;
double u;
Scanner scanner = new Scanner(System.in);
public int Methode()
{
s = scanner.nextInt();
return s;
}
now in the main method just call the method -
Auslesen a=new Auslesen();
System.out.println("The entered number is: "+a.Methode());
Im building a lexical/syntex analyzer for class. The problem I am having is when I try to access my static variable "lexems" or "tokens" from a method besides main they are NULL. When I use them in main (such as the lex.printList method) they are fine and filled with data.
Whats going on???
import java.io.IOException;
import java.util.ArrayList;
public class SyntaxAnalyzer {
public static int pos = 0;
public static ArrayList<String> lexems = new ArrayList<String>();
public static ArrayList<String> tokens = new ArrayList<String>();
public static String nextToken;
public static void main(String[] args) throws IOException {
LexicalAnalysis lex = new LexicalAnalysis();
lex.getFile();
lex.parseText();
ArrayList<String> lexems = lex.getLexems();
lex.printList(lexems);
ArrayList<String> tokens = lex.getTokens();
lex.printList(tokens);
//expr();
lex();
}
static void lex(){
//String lexem = lexems.get(pos);
//System.out.println(lexem);
nextToken = tokens.get(pos);
pos++;
}
}
You are overriding the lexems object with the local one so it is not static variable you are modifying inside main function.
To operate on the static one you should do
/*NOTHING HERE!!*/ lexems = lex.getLexems();
lex.printList(lexems);
...
The same issue with tokens occurs
/*NOTHING HERE!!*/ tokens = lex.getTokens();
lex.printList(tokens);
...
The problems are here:
ArrayList<String> lexems = lex.getLexems();
lex.printList(lexems);
ArrayList<String> tokens = lex.getTokens();
In you main function you do not modify the static variables but local ones (local in the main function).
Just change it to that:
lexems = lex.getLexems();
tokens = lex.getTokens();
You are creating another pair of variables in your main method, which happen to have same names as your static variables, and "overshadow" them within the scope of main method.
To fix it, you should not declare new variables, but initialise the existing ones:
public static void main(String[] args) throws IOException {
LexicalAnalysis lex = new LexicalAnalysis();
lex.getFile();
lex.parseText();
lexems = lex.getLexems();
lex.printList(lexems);
tokens = lex.getTokens();
lex.printList(tokens);
//expr();
lex();
}
This should help make the difference between the scopes used in your code :
public class MyClass{
private static int myInt;
public static void main(String[] args){
int myInt = 6;
printMyInt();
}
static void printMyInt(){ System.out.println(myInt); } // Prints 0 because uses the class field
}