Java logical OR as per user input - java

Requirement:
The program looks if a string is equal to the one or any of the characters entered by the user. The user may enter any numbers of entries separated by commas.
In essence the code should be
if user inputs one value (X) // in[0] = X;
if(str.equals(in[0]))
{
// do something
}
if user inputs two values (X,Y) // in[0] = X; in[1] = Y;
if(str.equals(in[0]) || str.equals(in[1]))
{
// do something
}
if user inputs three values (X,Y,Z) // in[0] = X; in[1] = Y; in[2] = Z;
if(str.equals(in[0]) || str.equals(in[1]) || str.equals(in[2]))
{
// do something
}
And so on......
As you can see I cannot write such a dynamic if statement.
I would have liked to have something like the below work. Any suggestions?
Trial code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class test {
public static void main (String[] args) throws Exception {
System.out.println("Enter the characters separated by commas");
BufferedReader consoleinput = new BufferedReader(new InputStreamReader(System.in));
String input = consoleinput.readLine();
input = input.toUpperCase();
String[] in = input.split(",");
String str = "N";
if (str.equals(in))
{
System.out.println("Match found");
}
else
{
System.out.println("No match");
}
}
}

What you want is some sort of loop.
foreach(string str : in) {
//code here
}

The Apache Commons CLI library provides an API for parsing command line options passed to programs

Do you look for something like this?
if (Arrays.asList(in).contains(str)) {
// do something
}

Related

Why is my radix sorting algorithm returning a partially sorted list?

First off I want to point out that this assignment is homework /but/ I am not looking for a direct answer, but rather at a hint or some insight as to why my implementation is not working.
Here is the given: We are provided with a list of words of 7 characters long each and are asked to sort them using the Radix Sorting Algorithm while using queues.
EDIT 1: Updated Code
Here is my code:
import java.util.*;
import java.io.File;
public class RadixSort {
public void radixSort() {
ArrayList<LinkedQueue> arrayOfBins = new ArrayList<LinkedQueue>();
LinkedQueue<String> masterQueue = new LinkedQueue<String>();
LinkedQueue<String> studentQueue = new LinkedQueue<String>();
//Creating the bins
for (int i = 0; i < 26; i++) {
arrayOfBins.add(new LinkedQueue<String>());
}
// Getting the file name and reading the lines from it
try {
Scanner input = new Scanner(System.in);
System.out.print("Enter the file name with its extension: ");
File file = new File(input.nextLine());
input = new Scanner(file);
while (input.hasNextLine()) {
String line = input.nextLine();
masterQueue.enqueue(line);
}
input.close();
} catch (Exception ex) {
ex.printStackTrace();
}
for (int p = 6; p >= 0; p--) {
for (LinkedQueue queue : arrayOfBins) {
queue.clear();
}
while (masterQueue.isEmpty() == false) {
String s = (String) masterQueue.dequeue();
char c = s.charAt(p);
arrayOfBins.get(c-'a').enqueue(s);
}
for (LinkedQueue queue : arrayOfBins) {
studentQueue.append(queue);
}
}
masterQueue = studentQueue;
System.out.println(masterQueue.size());
System.out.println(masterQueue.dequeue());
}
public static void main(String [] args) {
RadixSort sort = new RadixSort();
sort.radixSort();
}
}
I can see so many problems, I'm not sure how you get an answer at all.
Why do you have two nested outermost loops from 0 to 6?
Why don't you ever clear studentQueue?
The j loop doesn't execute as many times as you think it does.
Aside from definite bugs, the program doesn't output anything -- are you just looking at the result in the debugger? Also are you actually allowed to assume that the words will contain no characters besides lowercase letters?

Reversing a string with no stringbuilder and user input?

Hi I have to create a program that can take a string that a user inputs through a input box and display the string in reverse in a output box. I also can't use StringBuilder. Before I knew that, I was able to do this using StringBuilder
import java.lang.StringBuilder;
import javax.swing.JOptionPane;
public class reverse
{
public static void main(String[] args)
{
String string = JOptionPane.showInputDialog("Please input a string");
JOptionPane.showMessageDialog(null, new StringBuilder(string).reverse().toString());
}
}`
So after I found out that I can't use StringBuilder I tried to reprogram this and this is the code I came up with
import javax.swing.JOptionPane;
public class reversethisstring
{
public static void main(String[] args)
{
String reverseMe = JOptionPane.showInputDialog("Please input a string");
for (int i = 0; i < reverseMe.length(); i++) {
reverseMe = reverseMe.substring(1, reverseMe.length() - i)
+ reverseMe.substring(0, 1)
+ reverseMe.substring(reverseMe.length() - i, reverseMe.length());
}
JOptionPane.showMessageDialog(reverseMe);
}
}
Now I am getting a error on line 12 that says
"The method showMessageDialog(java.awt.Component, java.lang.Object) in the type javax.swing.JOptionPane is not applicable for the arguments (java.lang.String)"
The code worked fine when I used "system.out.println" on the last line instead of the JOptionPane. So how can I convert this to work in a output box?
showMessageDialog takes two arguments, the first one being a Component. You can fix your code by just passing in null:
JOptionPane.showMessageDialog(null, reverseMe);
Try to change this line:
JOptionPane.showMessageDialog(reverseMe);
To some thing like this:
JOptionPane.showMessageDialog (null, reverseMe, "Title", JOptionPane.ERROR_MESSAGE);
Or like this:
JOptionPane.showMessageDialog (null, reverseMe);
Apart from the mentioned showMessageDialog(null, reverseMe); here's anoher go at reversing the String that uses the fact that Strings are build from char[]s.
public static void main(String[] args) {
String string = JOptionPane.showInputDialog(null, "Please input a string");
String reversed = reverse(string);
showMessageDialog(null, reversed);
}
private static String reverse(String forward) {
char[] x = forward.toCharArray();
String reversed = "";
for(int i = x.length-1; i >= 0; --i) {
reversed += x[i];
}
return reversed;
}

Trouble matching states to capitals

I created two arrays and assigned states to one array and capitals to the other array that I got from a text file. The text file is formatted like this:
Colorado,Denver,
Wisconsin,Madison,
..........etc
My code is as follows:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class StatesAndCapitals {
public static void main(String[] args) throws FileNotFoundException {
FileInputStream is = new FileInputStream("capitals.txt");
Scanner input = new Scanner(is);
String[] states = new String[50];
String[] capitals = new String[50];
for (int i = 0; i < states.length; i++){
String currentLine = input.nextLine();
int a = currentLine.indexOf(",");
String states1 = currentLine.substring(0, a);
states[i] = states1;
int b = currentLine.lastIndexOf(",");
String capitals1 = currentLine.substring(a+1, b);
capitals[i] = capitals1;
}//end for loop
}
}
The point of my program is to ask "What is the capital of (blank)?"
Then I need to tell the person if they are correct or not. The problem I'm having is that I don't know how to check if, for example, Madison is the capital of Wisconsin. Any help would be appreciated.
public static void main(String[] args) {
Scanner userInput = null;
Scanner scanner = null;
try {
userInput = new Scanner(System.in);
scanner = new Scanner(new File("capitals.txt"));
while (scanner.hasNext()) {
String[] stateAndCapital = scanner.next().split(",");
System.out.println(String.format("What is the capital of %s?",
stateAndCapital[0]));
System.out.println(userInput.next().equals(stateAndCapital[1]));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
scanner.close();
userInput.close();
}
}
output:
What is the capital of Colorado?
dunno
false
What is the capital of Wisconsin?
Madison
true
Try using this:
public boolean isCapitalOfState(String capital, String state) {
for (int i = 0; i < state.length; i++) {
if (state[i].equals(state) && capitals[i].equals(capital)) {
return true;
}
}
return false;
}
It loops through the array of states and once it has found the match, it will check if the capital matches, if so return true. If it has not found anything it will by default return false.
Note though that there are a lot of easier ways to achieve your behaviour. Generally, Lists are superior to Arrays.
EDIT: I see your question asks for a bit more, we here cannot give you a full program to do it. However do keep in mind that when you've already obtained an index in state, that you can check the result way easier than this.
These are setup like parallel arrays correct? Meaning for example states[0] = colorado, and capitals[0] = denver, it looks this way but if it is indeed setup like this use the index of the state as the index for the capital and compare the input against that.
For example,
System.out.println("What is the capital of " + states[i]);
capital = input.nextLine();
if(capital.equals(capitals[i]){
return true;
}
else{
return false;
}

Parse different types of data from input java

Different lists of data will be entered on command line.
"J,A,V,A"
"4,H,11,V,3,H"
I need to store the first list in a char array. I also want to have the next line in a char array of "H,V,H" and an int array of "4,11,3". What is the best way to go about doing this? I'm hesitant to split on the comma because I don't know if the input is going to be separated by just a comma or a comma and a space. I'm having difficulty since when I use a scanner everything stays in a string, and when I try to split it the string becomes a string array.
I'm having difficulty since when I use a scanner everything stays in a string, and when I try to split it the string becomes a string array.
The following seems to work for me.. Only ran it in the debugger, but it workd on the two lines of input you provided.
import java.lang.System;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> ints = new ArrayList<Integer>();
ArrayList<Character> chars = new ArrayList<Character>();
Scanner console = new Scanner(System.in);
while (console.hasNext()) {
String line = console.next();
String[] tokens = line.split("\\s*,\\s*");
for (int i = 0; i < tokens.length; i++) {
if (isInteger(tokens[i])) {
ints.add(Integer.parseInt(tokens[i]));
} else if (isChar(tokens[i])) {
chars.add((char) tokens[i].indexOf(0));
}
}
}
console.close();
}
private static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch (NumberFormatException e) {
return false;
}
// only got here if we didn't return false
return true;
}
private static boolean isChar(String s) {
if (s.length() != 1) {
return false;
}
return true;
}
}

Java: Removing comments from string

I'd like to do a function which gets a string and in case it has inline comments it removes it. I know it sounds pretty simple but i wanna make sure im doing this right, for example:
private String filterString(String code) {
// lets say code = "some code //comment inside"
// return the string "some code" (without the comment)
}
I thought about 2 ways: feel free to advice otherwise
Iterating the string and finding double inline brackets and using substring method.
regex way.. (im not so sure bout it)
can u tell me what's the best way and show me how it should be done? (please don't advice too advanced solutions)
edited: can this be done somehow with Scanner object? (im using this object anyway)
If you want a more efficient regex to really match all types of comments, use this one :
replaceAll("(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)|(?://.*)","");
source : http://ostermiller.org/findcomment.html
EDIT:
Another solution, if you're not sure about using regex is to design a small automata like follows :
public static String removeComments(String code){
final int outsideComment=0;
final int insideLineComment=1;
final int insideblockComment=2;
final int insideblockComment_noNewLineYet=3; // we want to have at least one new line in the result if the block is not inline.
int currentState=outsideComment;
String endResult="";
Scanner s= new Scanner(code);
s.useDelimiter("");
while(s.hasNext()){
String c=s.next();
switch(currentState){
case outsideComment:
if(c.equals("/") && s.hasNext()){
String c2=s.next();
if(c2.equals("/"))
currentState=insideLineComment;
else if(c2.equals("*")){
currentState=insideblockComment_noNewLineYet;
}
else
endResult+=c+c2;
}
else
endResult+=c;
break;
case insideLineComment:
if(c.equals("\n")){
currentState=outsideComment;
endResult+="\n";
}
break;
case insideblockComment_noNewLineYet:
if(c.equals("\n")){
endResult+="\n";
currentState=insideblockComment;
}
case insideblockComment:
while(c.equals("*") && s.hasNext()){
String c2=s.next();
if(c2.equals("/")){
currentState=outsideComment;
break;
}
}
}
}
s.close();
return endResult;
}
The best way to do this is to use regular expressions.
At first to find the /**/ comments and then remove all // commnets. For example:
private String filterString(String code) {
String partialFiltered = code.replaceAll("/\\*.*\\*/", "");
String fullFiltered = partialFiltered.replaceAll("//.*(?=\\n)", "")
}
Just use the replaceAll method from the String class, combined with a simple regular expression. Here's how to do it:
import java.util.*;
import java.lang.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
String s = "private String filterString(String code) {\n" +
" // lets say code = \"some code //comment inside\"\n" +
" // return the string \"some code\" (without the comment)\n}";
s = s.replaceAll("//.*?\n","\n");
System.out.println("s=" + s);
}
}
The key is the line:
s = s.replaceAll("//.*?\n","\n");
The regex //.*?\n matches strings starting with // until the end of the line.
And if you want to see this code in action, go here: http://www.ideone.com/e26Ve
Hope it helps!
To find the substring before a constant substring using a regular expression replacement is a bit much.
You can do it using indexOf() to check for the position of the comment start and substring() to get the first part, something like:
String code = "some code // comment";
int offset = code.indexOf("//");
if (-1 != offset) {
code = code.substring(0, offset);
}
#Christian Hujer has been correctly pointing out that many or all of the solutions posted fail if the comments occur within a string.
#Loïc Gammaitoni suggests that his automata approach could easily be extended to handle that case. Here is that extension.
enum State { outsideComment, insideLineComment, insideblockComment, insideblockComment_noNewLineYet, insideString };
public static String removeComments(String code) {
State state = State.outsideComment;
StringBuilder result = new StringBuilder();
Scanner s = new Scanner(code);
s.useDelimiter("");
while (s.hasNext()) {
String c = s.next();
switch (state) {
case outsideComment:
if (c.equals("/") && s.hasNext()) {
String c2 = s.next();
if (c2.equals("/"))
state = State.insideLineComment;
else if (c2.equals("*")) {
state = State.insideblockComment_noNewLineYet;
} else {
result.append(c).append(c2);
}
} else {
result.append(c);
if (c.equals("\"")) {
state = State.insideString;
}
}
break;
case insideString:
result.append(c);
if (c.equals("\"")) {
state = State.outsideComment;
} else if (c.equals("\\") && s.hasNext()) {
result.append(s.next());
}
break;
case insideLineComment:
if (c.equals("\n")) {
state = State.outsideComment;
result.append("\n");
}
break;
case insideblockComment_noNewLineYet:
if (c.equals("\n")) {
result.append("\n");
state = State.insideblockComment;
}
case insideblockComment:
while (c.equals("*") && s.hasNext()) {
String c2 = s.next();
if (c2.equals("/")) {
state = State.outsideComment;
break;
}
}
}
}
s.close();
return result.toString();
}
I made an open source library (on GitHub) for this purpose , its called CommentRemover you can remove single line and multiple line Java Comments.
It supports remove or NOT remove TODO's.
Also it supports JavaScript , HTML , CSS , Properties , JSP and XML Comments too.
Little code snippet how to use it (There is 2 type usage):
First way InternalPath
public static void main(String[] args) throws CommentRemoverException {
// root dir is: /Users/user/Projects/MyProject
// example for startInternalPath
CommentRemover commentRemover = new CommentRemover.CommentRemoverBuilder()
.removeJava(true) // Remove Java file Comments....
.removeJavaScript(true) // Remove JavaScript file Comments....
.removeJSP(true) // etc.. goes like that
.removeTodos(false) // Do Not Touch Todos (leave them alone)
.removeSingleLines(true) // Remove single line type comments
.removeMultiLines(true) // Remove multiple type comments
.startInternalPath("src.main.app") // Starts from {rootDir}/src/main/app , leave it empty string when you want to start from root dir
.setExcludePackages(new String[]{"src.main.java.app.pattern"}) // Refers to {rootDir}/src/main/java/app/pattern and skips this directory
.build();
CommentProcessor commentProcessor = new CommentProcessor(commentRemover);
commentProcessor.start();
}
Second way ExternalPath
public static void main(String[] args) throws CommentRemoverException {
// example for externalPath
CommentRemover commentRemover = new CommentRemover.CommentRemoverBuilder()
.removeJava(true) // Remove Java file Comments....
.removeJavaScript(true) // Remove JavaScript file Comments....
.removeJSP(true) // etc..
.removeTodos(true) // Remove todos
.removeSingleLines(false) // Do not remove single line type comments
.removeMultiLines(true) // Remove multiple type comments
.startExternalPath("/Users/user/Projects/MyOtherProject")// Give it full path for external directories
.setExcludePackages(new String[]{"src.main.java.model"}) // Refers to /Users/user/Projects/MyOtherProject/src/main/java/model and skips this directory.
.build();
CommentProcessor commentProcessor = new CommentProcessor(commentRemover);
commentProcessor.start();
}
for scanner, use a delimiter,
delimiter example.
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class MainClass {
public static void main(String args[]) throws IOException {
FileWriter fout = new FileWriter("test.txt");
fout.write("2, 3.4, 5,6, 7.4, 9.1, 10.5, done");
fout.close();
FileReader fin = new FileReader("Test.txt");
Scanner src = new Scanner(fin);
// Set delimiters to space and comma.
// ", *" tells Scanner to match a comma and zero or more spaces as
// delimiters.
src.useDelimiter(", *");
// Read and sum numbers.
while (src.hasNext()) {
if (src.hasNextDouble()) {
System.out.println(src.nextDouble());
} else {
break;
}
}
fin.close();
}
}
Use a tokenizer for a normal string
tokenizer:
// start with a String of space-separated words
String tags = "pizza pepperoni food cheese";
// convert each tag to a token
StringTokenizer st = new StringTokenizer(tags," ");
while ( st.hasMoreTokens() )
{
String token = (String)st.nextToken();
System.out.println(token);
}
http://www.devdaily.com/blog/post/java/java-faq-stringtokenizer-example
It will be better if code handles single line comment and multi line comment separately . Any suggestions ?
public class RemovingCommentsFromFile {
public static void main(String[] args) throws IOException {
BufferedReader fin = new BufferedReader(new FileReader("/home/pathtofilewithcomments/File"));
BufferedWriter fout = new BufferedWriter(new FileWriter("/home/result/File1"));
boolean multilinecomment = false;
boolean singlelinecomment = false;
int len,j;
String s = null;
while ((s = fin.readLine()) != null) {
StringBuilder obj = new StringBuilder(s);
len = obj.length();
for (int i = 0; i < len; i++) {
for (j = i; j < len; j++) {
if (obj.charAt(j) == '/' && obj.charAt(j + 1) == '*') {
j += 2;
multilinecomment = true;
continue;
} else if (obj.charAt(j) == '/' && obj.charAt(j + 1) == '/') {
singlelinecomment = true;
j = len;
break;
} else if (obj.charAt(j) == '*' && obj.charAt(j + 1) == '/') {
j += 2;
multilinecomment = false;
break;
} else if (multilinecomment == true)
continue;
else
break;
}
if (j == len)
{
singlelinecomment=false;
break;
}
else
i = j;
System.out.print((char)obj.charAt(i));
fout.write((char)obj.charAt(i));
}
System.out.println();
fout.write((char)10);
}
fin.close();
fout.close();
}
Easy solution that doesn't remove extra parts of code (like those above)
// works for any reader, you can also iterate over list of strings instead
String str="";
String s;
while ((s = reader.readLine()) != null)
{
s=s.replaceAll("//.*","\n");
str+=s;
}
str=str.replaceAll("/\\*.*\\*/"," ");

Categories