I'm still trying to make the text editor to run with cmd but I'm stuck.
import java.util.Scanner;
public class TextEd {
Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
Editor editor = new Editor();
editor.copiedText();
}
}
class Editor {
Scanner scan = new Scanner(System.in);
public void copiedText() {
System.out.println("Paste your text here");
String text = scan.nextLine();
menu();
}
public void menu() {
System.out.println("Welcome to the text editor.\n"
+ "What do you want to do?\n"
+ "1. count characters"?;
int choice = scan.nextInt();
if (choice == 1) {
counting();
}
}
public void counting() {
System.out.println(text.length());
}
}
The problem is: everytime i try to execute i get an error "cannot find symbol 'text". I know I need to call it frim the other method, but hod do i do that?
Yoy need to make it a class field:
class Editor {
private Scanner scan = new Scanner(System.in);
private String text = "";
public void copiedText() {
System.out.println("Paste your text here");
text = scan.nextLine();
menu();
}
public void menu() {
System.out.println("Welcome to the text editor.\n"
+ "What do you want to do?\n"
+ "1. count characters"?;
int choice = scan.nextInt();
if (choice == 1) {
counting();
}
}
public void counting() {
System.out.println(text.length());
}
}
Also field scan in class TextEd seems to have no purpose and should therefore be removed.
You have declared text as a local variable in copiedText(). Local variables cannot be seen in other methods. Try setting a field variable (a private variable in the Editor class) that can be seen by all methods
your code has compile error because the parentheses in System.out.println() in menu are not closed properly.
you want to call a method of a text String in another method, so you can pass text to that method or just define it as a field in your class so that other methods can reach that variable.
import java.util.Scanner;
public class TextEd {
Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
Editor editor = new Editor();
editor.copiedText();
}
}
class Editor {
Scanner scan = new Scanner(System.in);
String text;
public void copiedText() {
System.out.println("Paste your text here");
text = scan.nextLine();
menu();
}
public void menu() {
System.out.println("Welcome to the text editor.\n"
+ "What do you want to do?\n"
+ "1. count characters?");
int choice = scan.nextInt();
if (choice == 1) {
counting();
}
}
public void counting() {
System.out.println(text.length());
}
}
be aware of blocks, every variable that is defined in other blocks or methods, is not reachable in other blocks or methods.
Related
public class BookstoreRun {
public static void main(String[] args) {
BookstoreMenu bm = new BookstoreMenu();
bm.mainMenu();
}
}
Here's the menu class:
public class BookstoreMenu {
private Scanner sc = new Scanner(System.in);
private BookstoreController bc = new BookstoreController();
public void mainMenu() {
System.out.println("1. SignUp");
System.out.println("2. Check members list");
System.out.println("Select menu : ");
int menu = sc.nextInt();
switch (menu) {
case 1: {
bc.createAccount();
break;
} case 2:
default:
System.out.println("...");
}
}
}
This is controller class where I made methods:
public class BookstoreController {
private Scanner sc = new Scanner(System.in);
public void createAccount() {
System.out.println("Let's get started");
System.out.print("Your name : ");
String[] strArray = new String[0];
String name = sc.nextLine();
strArray = saveId(strArray, name);
System.out.print(name + ", Nice to meet you!");
System.out.println(Arrays.toString(strArray));
}
public String[] saveId(String[] originArr, String name) {
String[] newArr = new String[originArr.length + 1];
System.arraycopy(originArr, 0, newArr, 0, originArr.length);
newArr[originArr.length] = name;
return newArr;
}
}
I'm trying to make a menu with just two options. The first option is Sign Up through createAccount(); and once I finish signing up, I want to go back to the menu class and choose option 2.
I was thinking I could approach the information of strArray in BookstoreController class by typing bc.~ under case 2 of the switch in the BookstoreMenu class, but I failed.
My question is: Is it possible to approach the value which was made in the local area of another class?
No you cannot. Welcome to the world of Object Oriented Programming OOP & design. One of the more important ideas of OOP is that you encapsulate data and then access it through method calls (or, for other languages, properties).
In this case you should return an Account class from createAccount(). Then you can have a method there to the strArray. That variable should be a field in the Account class and be renamed to something that reflects its purpose, rather than the types it is made up of (string and arrays).
Now, in modern Java, we store objects like accounts in lists, not arrays. Lists can be grown at your leisure. I've put the list into a field of the controller, so it can be maintained in the right controlled location.
Here is some example:
public class BookstoreRun {
public static void main(String[] args) {
BookstoreMenu bm = new BookstoreMenu();
bm.mainMenu(new Scanner(System.in), System.out);
}
}
public class BookstoreMenu {
private BookstoreController bc = new BookstoreController();
public void mainMenu(Scanner sc, PrintStream out) {
while (true) {
// this is a "try with resources", using a localized scanner
int menu;
out.println("1. SignUp");
out.println("2. Check members list");
out.println("9. Quit");
out.println("Select menu : ");
menu = sc.nextInt();
// either menu has been assigned, or an exception has been thrown, so we can now use it
switch (menu) {
case 1:
bc.createAccount(sc, out);
break;
case 2:
bc.displayAccounts(out);
break;
// always leave yourself an exit option
case 9:
out.println("Bye");
System.exit(0);
// the default should display an error or warning
default:
out.println("Unknown option, try again");
}
}
}
}
public class BookstoreController {
// the list of accounts that is initially empty, but may grow
private List<Account> accounts = new ArrayList<Account>();
public void createAccount(Scanner sc, PrintStream out) {
out.println("Let's get started");
out.println("Your name : ");
String name = sc.nextLine();
out.println(name + ", nice to meet you!");
Account account = new Account(name);
accounts.add(account);
}
public void displayAccounts(PrintStream out) {
for (Account account : accounts) {
out.println(account);
}
}
}
// this is the additional "data class"
public class Account {
private String name;
// constructor that assigns the name to the field
public Account(String name) {
this.name = name;
}
// a method to retrieve the property name
public String name() {
return name;
}
// this is what is called when it is printed using println (converted to string)
#Override
public String toString() {
return String.format("Account %s", name);
}
}
Hello sorry for this bold question but im not sure how to solve my needs on line 24 and 30 in the code. Also im getting error messages on line 33 and 22 so it would be awesome if you could solve those.
import java.util.Scanner;
public class CheckOrder {
public static Scanner userInput = new Scanner(System.in);
public static Scanner userInputStarters = new Scanner(System.in);
public static String menu;
public static String check;
public static String TheRestroom = "The Restroom";
public static String Restroom = "Restroom";
public static String Eat = "Eat";
public static String ToEat = "To Eat";
public static String restOrEat;
public static void main(String[] args) {
System.out.print("Hello and Welcome to the SOMETHING restaurant. Would you like to eat or use the restroom?");
public static restOrEat = userInput.NextInt();
if (restOrEat.equalsIgnoreCase(TheRestroom || Restroom)) {
System.out.println("Please go ahead to the restroom, it's over there.");
System.exit(1);
}
if (restOrEat.equalsIgnoreCase(Eat || ToEat)) {
System.out.print("What would you like to eat for starters? Press 1 for Cheese & Bacon, 2 for Sald (With options) and 3 for noodles");
public static String starter = userInputStarters;
}
}
}
The || operator can not be applied to java.util.String.
restOrEat.equalsIgnoreCase(Eat || ToEat);
The both variables Eat and ToEat are Objects from the the class java.util.String. That's why the || operator does not work in this case.
Change it to:
restOrEat.equalsIgnoreCase(Eat) || restOrEat.equalsIgnoreCase(ToEat);
This will work.
You can't write 'public static' the way you are writing inside the main method.
if (restOrEat.equalsIgnoreCase(TheRestroom) || restOrEat.equalsIgnoreCase(Restroom)) {
Replace both of your lines with above reference
First of all the if statements are incorrect, they are supposed to be like this if (restOrEat.equalsIgnoreCase(TheRestroom) || restOrEat.equalsIgnoreCase(Restroom)) {
Secondly, you can't have the public and static keywords infront of the variables inside methods.
So change the public static restOrEat (You're also missing the object definition) to int restOrEat (Seemingly you already defined it as a String in the class) and the NextInt is supposed to be nextInt()
Also check this out Java Naming Conventions
You have several problems:
Or condition (||) should be between to checks
if (restOrEat.equalsIgnoreCase(TheRestroom) || restOrEat.equalsIgnoreCase(Restroom)) { }
You defined restOrEat as class variable but redefined it (sort of) in main
public static restOrEat = userInput.NextInt();
public static is not valid syntax for a method variable (not even separately) and you don't have the type.
userInput.NextInt(); will return int but restOrEat is String. Use userInput.next() instead.
First of all in a main method you can't use public static. Also restOrEat sounds like is supposed to be a yes or no string, so you can't say nextInt(). use either next() if its just one word or nextLine() if you want a whole line. And in the if statements you can't use the || operator inside the equalsIgnoreCase() call but you need to make two and put the || in the middle.
Try this if it fits what you need.
import java.util.Scanner;
public class CheckOrder {
public static Scanner userInput = new Scanner(System.in);
public static Scanner userInputStarters = new Scanner(System.in);
public static String menu;
public static String check;
public static String TheRestroom = "The Restroom";
public static String Restroom = "Restroom";
public static String Eat = "Eat";
public static String ToEat = "To Eat";
public static String restOrEat;
public static void main(String[] args) {
System.out.print("Hello and Welcome to the SOMETHING restaurant. Would you like to eat or use the restroom?");
restOrEat = userInput.next();
if (restOrEat.equalsIgnoreCase(TheRestroom) || restOrEat.equalsIgnoreCase(Restroom)) {
System.out.println("Please go ahead to the restroom, it's over there.");
System.exit(1);
}
if (restOrEat.equalsIgnoreCase(Eat) || restOrEat.equalsIgnoreCase(ToEat)) {
System.out.print("What would you like to eat for starters? Press 1 for Cheese & Bacon, 2 for Sald (With options) and 3 for noodles");
int starter = userInputStarters.nextInt();
}
}
}
import java.util.Scanner;
class CheckOrder {
public static Scanner userInput = new Scanner(System.in);
public static Scanner userInputStarters = new Scanner(System.in);
public static String menu;
public static String check;
public static String TheRestroom = "The Restroom";
public static String Restroom = "Restroom";
public static String Eat = "Eat";
public static String ToEat = "To Eat";
public static String restOrEat;
public static void main(String[] args) {
System.out.print("Hello and Welcome to the SOMETHING restaurant. Would you like to eat or use the restroom?");
restOrEat = userInput.next();
if (restOrEat.equalsIgnoreCase(TheRestroom)||restOrEat.equalsIgnoreCase(Restroom)) {
System.out.println("Please go ahead to the restroom, it's over there.");
System.exit(1);
}
if (restOrEat.equalsIgnoreCase(Eat)||restOrEat.equalsIgnoreCase(ToEat)) {
System.out.print("What would you like to eat for starters? Press 1 for Cheese & Bacon, 2 for Sald (With options) and 3 for noodles");
int starter = userInputStarters.nextInt();
}
}
}
Here is the solution for your problem.
I'm writing some code for a text based game for my Computer Science class, but I'm having some problems with this code
(java code).
The all the code works until I put in the if/else statements, so I want to know where I should be putting the statements at.
(Error Message)
Code:
import java.util.Scanner;
import java.util.ArrayList;
class Progress {
public String udc;
public String u = "up";
public String d = "down";
public void start() {
System.out.println("Hello.");
}
public void c1() {
Scanner name=new Scanner(System.in);
System.out.println("What's your name?");
System.out.println("Hello "+name.nextLine()+".");
}
public void uod() {
Scanner ud = new Scanner(System.in);
System.out.println("Up or down?");
udc = ud.nextLine();
}
public void uodc() {
System.out.println("going "+udc+".");
}
public void end() {
System.out.println("Press any key to exit");
}
}
public class APGame {
public static void main(String[] args) {
Progress p =new Progress();
p.start();
p.c1();
p.uod();
if (u.equals(udc)) {p.uodc();}
else {p.oud();}
p.end();
}}
u and udc variables are defined inside another class, that is Progress, and should be accessed (as they are public), by p.u and p.udc.
if (p.u.equals(p.udc)) ...
udc and u are instance variables of the class Progress. So the problem with the if-else statement is that you are not referencing udc from any object of the Progress class. To fix it do:
if(p.u.equals(p.udc) {
p.uodc();
}else{
p.uod();
}
So i've been messing around with String data types in the constructor of my class file, and while everything compiles correctly, when I run the application file, the program doesn't give the desired result. I kept it short to see if it would work, so my class file is as follows:
public class StringPractice
{
private String color;
private String brand;
public StringPractice() {
String color = "";
String brand = "";
}
public StringPractice(String clor, String brnd) {
setColor(clor);
setBrand(brnd);
}
public void setColor(String clor) {
if (clor.equalsIgnoreCase("Red")) {
color = clor;
}
else {
System.out.println("We dont't carry that color");
}
}
public void setBrand(String brnd) {
if (brnd.equalsIgnoreCase("Gibson")) {
brand = brnd;
}
else {
System.out.println("We do not carry that brand");
}
}
public String getColor() {
return color;
}
public String getBrand() {
return brand;
}
public void display() {
System.out.println("Our brands are: " + brand + "Our colors are: " + color);
}
My application file is as follows:
import java.util.Scanner;
public class UseStringPractice
{
public static void main(String[] args)
{
String brand = "";
String color = "";
Scanner keyboard = new Scanner(System.in);
StringPractice Guitar1;
System.out.println("Please enter the brand you would like");
brand = keyboard.next();
System.out.println("Please enter the color you would like");
color = keyboard.next();
Guitar1 = new StringPractice(brand, color);
Guitar1.display();
}
}
What am I doing incorrectly? Am I using the wrong methods to parse the information from scanner? Or am I using equalsIgnoreCase incorrectly? This is my first attempt at implementing these methods, so I may be wayyy off for all I know. When I run the application class, my result is that of the trailing else clause, or, "We do not carry those brands" or "We don't carry that color". Then, in my display statement, the variable names are replaced with "null". This is all for practice so any insight would be fantastic. Thanks!
Your arguments being passed to your constructor should be flipped.
In your application:
Guitar1 = new StringPractice(brand, color);
but in your code:
public StringPractice(String clor, String brnd) {
how do I get the read txt file into the main class?
//main class
public class mainClass {
public static void main(String[]args) {
load method = new load("Monster");
}
}
//scanner class
public class load {
public static void loader(String... aArgs) throws FileNotFoundException {
load parser = new load("resources/monsters/human/humanSerf.txt");
parser.processLineByLine();
log("Done.");
}
public load(String aFileName){
fFile = new File(aFileName);
}
public final void processLineByLine() throws FileNotFoundException {
//Note that FileReader is used, not File, since File is not Closeable
Scanner scanner = new Scanner(new FileReader(fFile));
try {
//first use a Scanner to get each line
while ( scanner.hasNextLine() ){
processLine( scanner.nextLine() );
}
}
finally {
scanner.close();
}
}
public void processLine(String aLine){
//use a second Scanner to parse the content of each line
Scanner scanner = new Scanner(aLine);
scanner.useDelimiter("=");
if ( scanner.hasNext() ){
String name = scanner.next();
String value = scanner.next();
log("Stat is : " + quote(name.trim()) + ", and the value is : " + quote(value.trim()) );
}
else {
log("Empty or invalid line. Unable to process.");
}
}
public final File fFile;
public static void log(Object aObject){
System.out.println(String.valueOf(aObject));
}
public String quote(String aText){
String QUOTE = "'";
return QUOTE + aText + QUOTE;
}
}
Which method do I call from the main class and what variables do I return from that method if I want the text from the file. If anyone has a website that can help me learn scanner(got this source code of the internet and only sort of understand it from JavaPractises and the sun tutorials) that would be great. thanks
First, you probably want to follow standard Java naming conventions - use public class MainClass instead of mainClass.
Second, for your methods, the public has a specific purpose. See here and here. You generally want to label methods as public only as necessary (in jargon, this is known as encapsulation).
For your question - in the Load class, you can append all the text from the file to a String, and add a public getter method in Load which will return that when called.
Add this at the start of Load:
public class Load {
private String fileText;
// ... rest of class
And add this getter method to the Load class. Yes, you could simply mark fileText as public, but that defeats the purpose of Object-Oriented Programming.
public getFileText(String aFileName){
return fileText;
}
Finally, use this new method for log. Note that there is no need to use Object.
private static void log(String line) {
System.out.println(line);
fileText += aObject;
}
You can now get the read file into the main class by calling method.getFileText()
Code was TL;DR
If you want to get all of the data from the load class's .txt file, then you need to write a method in load to get the lines. Something like this would work:
public String[] getFileAsArray() {
ArrayList<String> lines = new ArrayList<String>();
Scanner in = new Scanner(fFile);
while(in.hasNextLine())
lines.add(in.nextLine();
String[] retArr = new String[lines.size()];
return lines.toArray(retArr);
}