Below is just an example of a java program using console operator and the program should be able to compile fine, but for some reason, my eclipse is not able to read "Console"
operator? please Help!.
public class Dot_operator {
public static void main (String [] args){
String name3 = Console.readLine("hello");
System.out.println(name3);
}
}
Console#readLine() is an instance method. You would need an instance of Console to invoke it.
Console console = System.console();
String name3 = console.readLine("hello");
System.out.println(name3);
Of course, you would need to import java.io.Console. Note that, this will thrown a NPE when run on eclipse, as System.console() will give you null. You should better use Scanner class here.
You probably made a simple typo: you didn't close the bracket next to the args:
public class Dot_operator {
public static void main (String [] args) {
Scanner sc = new Scanner(System.in);
System.out.println("hello");
String name3 = sc.nextLine();
System.out.println(name3);
}
}
This works on my machine.
Related
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.
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
I'm struggling with a specific method which takes in a String parameter. The promptString method will print its parameter to the user as a prompt, and then return a String that is the result of reading the console via the nextLine() method. For this program you will use nextLine() exclusively.
I've prompted the user with a question using a parameter, and then used nextLine to read the string but after that I am a bit lost. How can I get the method to print to the console?
import java.util.*;
public class StarWarsName{
public static void main (String [] args) {
promptString("Enter your first name: ");
}
public static String promptString (String n) {
Scanner console = new Scanner(System.in);
String first = console.nextline();
return first.trim();
}
}
I think you are over-thinking this thing. Just print it to the console.
public static void main(String[]args){
String result = promptString("Enter your first name: ");
System.out.println(result);
}
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.");
}
}
}
I made a class Anagrams that writes the permutations of the words in a sentence and when I run the compiled program as java Anagrams "sentence1" "sentence2"... It should generate the permutations of each of the sentences. How would I get it to do that?
import java.io.*;
import java.util.Random;
import java.util.ArrayList;
import java.util.Collections;
public class Anagrams
{
...
public static void main(String args[])
{
String phrase1 = "";
System.out.println("Enter a sentence.");
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
try { phrase1 = input.readLine(); }
catch (IOException e) {
System.out.println("Error!");
System.exit(1);
}
System.out.println();
new Anagrams(phrase1).printPerms();
}
}
this is what i have so far i just need it to run on "sentence1" "sentence2" ...
when i type the command java Anagrams "sentece1" "sentence2" ...
ive already compiled it using javac Anagrams.java
From your comment I think your only question is how to use command line arguments to solve the task:
Your main method is looking like this:
public static void main(String args[])
but should look like this
public static void main(String[] args)
You see that there is an array of strings that holds the command line arguments. So if your executing your code with
java Anagrams sentence1 sentence2
Then the array has the length 2. In the first place (args[0]) there is the value sentence1 and in the second place (args[1]) there is the value sentence2.
An example code that prints all your command line arguments looks like this:
public static void main (String[] args) {
for (String s: args) {
System.out.println(s);
}
}
Now you should be able to use your anagram algorithm for each command line argument.
Here's a simple example of getting the arguments from the command line.
Bear in mind that this is open to "IndexOutOfBoundsException"s if you don't provide enough arguments, so make sure to check that in your code!
class ArgsExample {
public static void main(String[] args) {
System.out.println(args[0]);
System.out.println(args[1]);
}
}
C:\Documents and Settings\glow\My Documents>javac ArgsExample.java
C:\Documents and Settings\glow\My Documents>java ArgsExample "This is one" "This
is two"
This is one
This is two
C:\Documents and Settings\glow\My Documents>
Varargs would allow you to use an indeterminate number of strings in a method signature, if that's what you're looking for. Otherwise, Roflcoptr is right if it's a question of passing arguments into main.