How to proceed with making an in - BlueJ Java file manager - java

I know that it is a bit of a noob program, but I'm slowly getting confused. The 'down' function is going to act like cd and the 'up' function would act like cd..
I have no clue how to allow the user to create a file or folder. I attempted using arrayLists instead of arrays but couldn't sort out the errors. Any help would be appreciated.
import java.util.Scanner;
class FileManager {
//array of arrays will go here
String Dir[] = {"UserOne"};
String SystemFolders [] = {"Documents","","",};
String SubFiles [] = {"","","","","",""};
String Nav [][] = { Dir, SystemFolders, SubFiles};
int levelCounter = 0;
public void main(String[]args) {
Scanner sc = new Scanner (System.in);
System.out.println("Enter a command");
String command = sc.next();
if (command.compareTo("down") == 0)
down();
//else if is on the way
}
void down () {
//This will execute when the command is 'down'
System.out.println(Nav[++levelCounter]);
}
void up () {
//This will execute when the command is 'up'. It acts like cd..
System.out.println(Nav[--levelCounter]);
}
}

If this is the entry point of your program then you need to declare your main method as static, like so
public static void main(String[] args)
Then to access the methods in your FileManager class in your main method you need to create an instance of your class in your main method. Like this
public static void main(String[]args) {
FileManager fm = new FileManager(); // Creates an instance
Scanner sc = new Scanner (System.in);
System.out.println("Enter a command");
String command = sc.next();
if (command.equals("down")) // equals will suffice in this case
// or equalsIgnoreCase() if you dont want case to be a problem
fm.down(); // Notice now this calls the down method from the instance
//else if is on the way
}
Then look at this to example to create files or this to create folders

Related

How to put multiple programs into one class?

I have made two programs for an assignment. Now my professor wants me to put both programs into the same file and use a switch to create a menu where the user can use to choose what program they want to run. How do I do this? I will copy-paste both of my original programs below.
Program 1:
import java.util.Scanner;
public class ReadName {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Please type in your full name: ");
String names = scanner.nextLine();
String[] namesSep = names.split(" ");
int lastString = namesSep.length - 1;
System.out.println(namesSep[0]);
System.out.println(namesSep[lastString]);
}
}
Program 2:
import java.util.Scanner;
public class FindSmith {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Type in your list of names: ");
String names = scanner.nextLine();
String[] namesSep = names.split(",");
for (int i=0; i<namesSep.length; i++) {
if (namesSep[i].contains("Smith")) {
System.out.println(namesSep[i]);
}
}
}
}
You have two classes that do work in a single main() method each.
Start with: moving the content of that main() methods into another static method within each class, like:
import java.util.Scanner;
public class ReadName {
public static void main(String[] args) {
askUserForName();
}
public static void askUserForName() {
Scanner scanner = new Scanner(System.in);
System.out.print("Please type in your full name: ");
...
}
}
Do that for both classes, and make sure that both classes still do what
you want them to do.
Then create a third class, and copy those two other methods into the new class.
Then write a main() method there, that asks the user what to do, and then
runs one of these two methods from there.
Alternatively, you could also do
public class Combo {
public static void main(String[] args) {
...
if (userWantsToUseClassOne) {
Readme.main(new String[0]);
} else {
FindSmith.main(...
In other words: as long as you keep your classes in the same directory, you can directly re-use what you already have. But it is much better practice to put your code into meaningful methods, like I showed first.
As you might know, each Java program only has a single entry point; defined by the method public static void main(String[] args). As each class can define this method only once and you have to specify the class the method is in in your META-INF.MF file, it is impossible to have multiple entry points.
So you have to implement the logic that controls the program flow and respects the user's choice on your own. You can e.g. ask the user via the command line what kind of subprogram they want to execute.
you can use multiple method instead of multiple class . and call all method from your main method should be solve your problem.....
public class Combo{
public void readName(){
// place here all code form main method block of ReadName class
}
public void findSmith(){
// place here all code form main method block of FindSmith class
}
public static void main(String[] args) {
Combo c = new Combo();
c.readName();
c.findSmith();
}
}
Rather than creating two classes, you can create single class with one main method. Where you can create 3 switch cases.
1) To call ReadName (RN)
2) To call FindSmith (FS)
3) To break the code (BR)
After every execution you can again call main method. (Optional) I have added that to continue the flow.
package test.file;
import java.util.Scanner;
public class Test {
private final static Scanner scanner = new Scanner(System.in);
//public class ReadName
public static void main(final String[] args) {
switch (scanner.nextLine()) {
case "FS" :
findSmith();
break;
case "RN" :
readName();
break;
case "BR" :
break;
default :
System.out.println("Please enter valid value. Valid values are FS and RN. Enter BR to break.");
main(null);
}
}
private static void findSmith() {
System.out.println("Type in your list of names: ");
final String names = scanner.nextLine();
final String[] namesSep = names.split(",");
for (int i = 0; i < namesSep.length; i++) {
if (namesSep[i].contains("Smith")) {
System.out.println(namesSep[i]);
}
}
System.out.println("Please enter valid value. Valid values are FS and RN. Enter BR to break.");
main(null);
}
private static void readName() {
System.out.print("Please type in your full name: ");
final String names = scanner.nextLine();
final String[] namesSep = names.split(" ");
final int lastString = namesSep.length - 1;
System.out.println(namesSep[0]);
System.out.println(namesSep[lastString]);
System.out.println("Please enter valid value. Valid values are FS and RN. Enter BR to break.");
main(null);
}
}
Welcome to this community! As #Stultuske comments, your better approach is convert your main methods to regular methods and invoke them depending on the user's input.
The steps you should follow are:
Join both main methods to a single class file.
Convert both main methods to regular methods:
Change their name from "main" to any other name. Usually, using their functionality as a name is a good practice. In your case, you can use the class names you already defined ("ReadName" and "FindSmith").
Remove their input parameter "args": as they are no more the main method of a class, they won't be reciving any args parameter, unless you specify it.
Define a new main method which reads from the scanner and call your new methods acordingly to the user input.

How to access input variable from another class? java

Trying to get the 1st class to recognize what the user inputs in the 2nd class. Any ideas as to what is going wrong here? The 2nd class works fine, but when i try to call 'input' from the main class, it says that 'input' cannot be resolved. Any suggestions and pointers much appreciated. Thanks for your time.
1st class:
public class Filter {
public static void main(String[] args) throws IOException {
BufferedReader in4 = new BufferedReader(new StringReader(automata.input));
String s = input.readLine();
while (automata.UserInput()==true){
if (automata.accepts(s)) System.out.println(s);
s = input.readLine();
}
}
}
2nd class:
public class automata extends Filter {
public static String input;
public static boolean UserInput() {
System.out.println("Please enter test data: ");
Scanner user_input = new Scanner(System.in);
input = user_input.next();
if (accepts(input) == true){
System.out.print("works");
return true;
} else {
System.out.println("Problem");
return false;
}
}
2nd class should look like:
public class Automata { // we use upper case for class names
public String input; // or better private and use a get-method
public Automata() {} // constructor
public boolean readUserInput() { // lower case here
System.out.println("Please enter test data: ");
Scanner user_input = new Scanner(System.in);
String nextInput = user_input.next();
input += nextInput; // otherwise you overwrite your current input
/*if (accepts(input) == true){
System.out.print("works");
// return true;
} else {
System.out.println("Problem");
return false;
}*/
// It is a terrible idea to return every time a single word is read
// rather read the whole String and then check if it is accepted
if (accept(input)) // whole String is checked
return true;
return false;
}
// in case the input variable is private
public String getInput() {
return input;
}
}
And then you have to access the class in this way:
public class Filter {
public static void main(String[] args) throws IOException {
Automata automata = new Automata();
if (automata.readUserInput()) {
// BufferedReader in4 = new BufferedReader(new StringReader(automata.getInput())); or automata.input in case it is public
// I don't understand why you want to read the input here again step by step
// rather read the whole input here
String userInput = automata.getInput();
}
}
}
You are confused with two different things: Class and Object. The Object is an Instance of the Class. Without understanding this you cannot understand what is wrong here.
Calling, for example Automata automata = new Automata() creates new Object of the class Automata.
"Extends" never helps you to get to the variables. It may help you to extend the current class and to use the methods that have been implemented in parent class, but you can never get to the pointers on the address spaces of that parent class.
To access a variable of another object you should declare public getter method for that variable in that class.
I think you need to replace
String s = input.readLine();
by
String s = in4.readLine(); in Filter class.
as readLine() is a method of BufferedReader Class
Try to rename the name of BufferedReader in input like this:
BufferedReader input = new BufferedReader(new StringReader(automata.input));
I think you have a typo..
Change input in the 1st class to in4.
'input' variable is declared in the 2nd class and you are trying to access it in the 1st class which is really impossible.
In class Filter, You do not have any member named input, due to which compile time exception is coming at input.readLine();.
From the context of your program, it appears that in4 should be used instead of input.
public class Filter {
public static void main(String[] args) throws IOException {
BufferedReader in4 = new BufferedReader(new StringReader(automata.input));
String s = in4.readLine();
while (automata.UserInput()==true){
if (automata.accepts(s)) System.out.println(s);
s = in4.readLine();
}
}
}

How do i call a class in the main method java?

OK im kinda new in java and i made this averaging program in one class, but now if i want to like call it from another class, then how do i do it?I tryed some object stuff but its hard to understand for.
this is the code and i want this program to start when i call it.
package Gangsta;
import java.util.Scanner;
public class okidoki {
public static void main(String []args){
Scanner input = new Scanner(System.in);
double average, tests, grades, total = 0;
int cunter = 1, start = 0;
System.out.println("Press 2 to start averaging, or press 1 to end");
start = input.nextInt();
while (cunter<start){
System.out.println("Enter how many tests u have");
tests = input.nextDouble();
System.out.println("Enter tests grades");
int counter = 0;
while (counter<tests){
counter++;
grades = input.nextDouble();
total = grades+total;
}
average = total/tests;
System.out.println(average);
System.out.println("Press 3 to end or 1 to average again");
cunter = input.nextInt();}
}
}
this is the code where i want to execute it
package Gangsta;
public class tuna {
public static void main(String []args){
okidoki okidokiObject = new okidoki();
System.out.println(okidokiObject);
}
}
In java the main method is the main (it's in the name) entry point of a program. That said, there is only one main in your program. Nevertheless if you want to have your code wrapped in another class just do it:
public class MyClass {
public void myFancyMethod() {
Scanner input = new Scanner(System.in);
//....rest of
//....your code
counter = input.nextInt();
}
}
and access it like:
MyClass myClassObject = new MyClass();
myClassObject.myFancyMethod();
You should really start reading (or read them again) the fundamentals of object oriented programming languages, naming conventions etc, because this is something you should understand to make progress in programming.
Object-Oriented Programming Concepts in Java
For now, you can just do this in tuna.java to achieve what you want:
package Gangsta;
public class tuna {
public static void main(String []args){
okidoki okidokiObject = new okidoki();
okidokiObject.main()
}
}
System.out.println(okidokiObject) prints Gangsta.okidoki#659e0bfd because it is the hashcode of your object (Hashcode is something like an ID, See Object toString()). You usually do not want to print objects, but invoke their methods.
If you change your main method in okidoki class to constructor it will work exactly like you wish !
Example:
Example.java
public class Example {
public Example() {
System.out.println("Example class constructed");
}
}
Main.java
public class Main {
public static void main(String[] args) {
System.out.println("Program started.Constructing Example class");
Example exClass = new Example();
System.out.println("Program finished.");
}
}

Error reached end of file while parsing

This is my Java class
import java.util.Scanner;
public class first {
public static void main(String args[]);
int right_number, user_input;
right_number = 6;
Scanner in = new Scanner(System.in);
System.out.println("Enter a number between 1 and 10");
user_input = input.nextInt();
if(user_input = right_number) {
System.out.println("That is the right number!");
}
else {
System.out.println("Aww, try again by typing java first into commad line.");
}
}
It keeps saying this:
Error reached end of file while parsing.
Can anyone help?
This is the first problem:
public static void main(String args[]);
You're not actually declaring a method body here. It should be:
public static void main(String[] args) {
// Method body goes here
}
You should only use a ; at the end of a method declaration for abstract methods (including those which are implicitly abstract in an interface). If you haven't got to abstract methods yet, just ignore that for the moment - basically use braces to provide a method body.
(The String[] args vs String args[] isn't a problem as such, but this version is preferred as a matter of style... as would naming your class First rather than first... there are various other style issues here, but I'll leave it at that for now.)
The fact that your class "tries" to end directly after an else statement should be a warning bell - an else statement can only appear in a method or constructor, so there has to be a brace to close that method/constructor and then a brace to close the class declaration itself. Likewise, the indentation should warn you of that - assuming you're using an IDE to perform the indentation, any time you find yourself writing method body statements which are only one level of indentation further than the class declaration, that suggests you have a problem somewhere - look up the file to see where it starts.
The code has a lot of mistakes like :
1.
public static void main(String args[]);
it should be
public static void main(String args[])
{
// every thing should be inside this
}
2.
You have declared your scanner object to be in , but you are doing user_input = input.nextInt(); , which should be user_input = in.nextInt();
3.
if(user_input = right_number) should say if(user_input == right_number) because = is the assignment operator, to compare you should use ==
This is the right code :
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
int right_number, user_input;
right_number = 6;
Scanner in = new Scanner(System.in);
System.out.println("Enter a number between 1 and 10");
user_input = in.nextInt();
if(user_input == right_number) {
System.out.println("That is the right number!");
}
else {
System.out.println("Aww, try again by typing java first into commad line.");
}
}
}

Why can't I print a variable that is provided by user inside a loop?

I apologize if the answer to this question is so obvious I shouldn't even be posting this here but I've already looked up the error compiling the following code results in and found no explanation capable of penetrating my thick, uneducated skull.
What this program is meant to do is get 2 integers from the user and print them, but I have somehow managed to mess up doing just that.
import java.util.Scanner;
public class Exercise2
{
int integerone, integertwo; //putting ''static'' here doesn't solve the problem
static int number=1;
static Scanner kbinput = new Scanner(System.in);
public static void main(String [] args)
{
while (number<3){
System.out.println("Type in integer "+number+":");
if (number<2)
{
int integerone = kbinput.nextInt(); //the integer I can't access
}
number++;
}
int integertwo = kbinput.nextInt();
System.out.println(integerone); //how do I fix this line?
System.out.println(integertwo);
}
}
Explanation or a link to the right literature would be greatly appreciated.
EDIT: I want to use a loop here for the sake of exploring multiple ways of doing what this is meant to do.
Remove the int keyword when using the same variable for the second time. Because when you do that, it is essentially declaring another variable with the same name.
static int integerone, integertwo; // make them static to access in a static context
... // other code
while (number<3){
System.out.println("Type in integer "+number+":");
if (number<2)
{
integerone = kbinput.nextInt(); //no int keyword
}
number++;
}
integertwo = kbinput.nextInt(); // no int keyword
And it needs to be static as well since you're trying to access it in a static context (i.e) the main method.
The other option would be to declare it inside the main() method but before your loop starts so that it'll be accessible throughout the main method(as suggested by "Patricia Shanahan").
public static void main(String [] args) {
int integerone, integertwo; // declare them here without the static
... // rest of the code
}
How about:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner kbinput = new Scanner(System.in);
System.out.println("Type in an integer: ");
int integerone = kbinput.nextInt();
System.out.println("Type another: ");
int integertwo = kbinput.nextInt();
System.out.println(integerone);
System.out.println(integertwo);
}
}

Categories