Java program help - java

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.

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.

Hello, I need help on creating a Star Wars name generator using specific instructions

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);
}

creating a new line for string

made a program that counts and outputs users based on user input. I want the program to display the names one below the other with the line break but stuck on how to. the code is below:
package uk.ac.reading.cs2ja16.Glen.Stringtest;
import java.util.Arrays;
import java.util.Scanner;
public class stringnames {
public static String[] countNames (String names) {
// Create Scanner object
#SuppressWarnings("resource")
Scanner names1 =new Scanner(System.in);
// Read a string
String read= names1.nextLine();
// Split string with space
String numPeople[]=read.trim().split(" ");
System.out.println("The Number of names inputted is: "+ numPeople.length);
return numPeople;
}
public static void main(String[ ] args){
System.out.println("Enter the amount of names you want(make sure you make space for each name):\n");
String[] namesout = countNames(null);
System.out.println(Arrays.toString(namesout));
}
}
First of all, the countNames method does not need a parameter, so delete that String names thingy in the method declaration. And delete the word null in your method call.
Now, you can either use a for loop or use one of the methods in the new Stream API if you're using Java 8.
I'll show you both ways.
For loop:
for (String name: namesout) {
System.out.println(name);
}
the println method automatically adds a new line character at the end of the string that you want to print.
Stream API:
Arrays.stream(namesout).forEach(System.out::println);

Console operator in java is not able to compile

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.

Scanner Class to create tokens of an input file

I have written the following code in java to open another .java file and create tokens (using scanner class)
import java.io.FileReader;
import java.util.Scanner;
public class scanner1 {
public static void main(String[] arg) throws Exception
{
FileReader fin = new FileReader("mysourcefile.java");
Scanner scan=new Scanner(fin);
scan.useDelimiter(" "); // the delimiter pattern required
while(scan.hasNext()) {
System.out.println(scan.next());
}
}
}
My task is to create the tokens of complete Java file and the delimiters should be treated as the tokens also.
So what should be the delimiter pattern to use here in scan.useDelimiter("")?
UPDATE:
The above task was completed using the stringtokenizer. But I don't know the exact pattern of the delimiter to create tokens for a .java file. Can I have an answer about what the delimiter pattern to use in the given case ?
import java.util.*;
public class sstring2
{
public static void main(String[] args)
{
String s = "a=(b+c); String st='hello! my dear';";
StringTokenizer st = new StringTokenizer(s, "[ =+';().*{}[],!##$%^&/]", true);
while(st.hasMoreTokens()){
System.out.println(st.nextToken());
}
}
}
This code gives the correct results.
Take a look at the java.lang.instrument packagae. It provides some nice APIs to transform an already loaded class. The retransformation allows to change method bodies as in your case. Here's the link
it may be any character on which you want to terminate the input.

Categories