I wrote this code.
I am new to Java and willing to develop my skills,so I wrote this code,in order to learn Arrays,one developer suggested HashSet,I am looking forward for new suggestions.
import java.io.*;
public class dictionary
{
public static void main(String args[])
{
String[] MyArrayE=new String[5];
String[] MyArrayS=new String[5];
MyArrayE[0]="Language";
MyArrayE[1]="Computer";
MyArrayE[2]="Engineer";
MyArrayE[3]="Home";
MyArrayE[4]="Table";
MyArrayS[0]="Lingua";
MyArrayS[1]="Computador";
MyArrayS[2]="Ing.";
MyArrayS[3]="Casa";
MyArrayS[4]="Mesa";
System.out.println("Please enter a word");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String word= null;
try {
word= br.readLine();
} catch (IOException e) {
System.out.println("Error!");
System.exit(1);
}
System.out.println("Your word is " + word);
for(int i=0; i<MyArrayE.length; i++)
{
if(word.equals(MyArrayS[i]))
{
System.out.println(MyArrayE[i]);
}
}
}
}
My Question: What about if the user inputs a word not in MyArrayS, I want to check that and print a statement like "Word does not exist".
I think that it might look like:
if(word!=MyArrayS)
{
System.out.println("Word does not exist");
}
Thanks
You can simply use the .Contains(String) method to determine whether the word is contained within the array.
You have to check every element of the array to see that it's not there. So your code would actually look like:
int c;
boolean found = false;
for(c = 0;c < MyArrayS.length;c++) {
if(MyArrayS.compareTo(word) == 0) {
found = true;
}
}
if(!found) {
System.out.println("Word does not exist");
}
Related
I have a code which will read Strings from a text file and store it in a String array. Then the user would enter a String and check if it exists inside the array. Sadly it always print an error
Name not found on my database :<.
Where did I go wrong?
import java.util.Scanner;
import java.io.*;
class MaleNames{
static String names[] = new String[1362];
static Scanner readFile;
static String n;
static int i = 0;
static int x = 0;
public static void main(String args[]) throws Exception{
try {
readFile = new Scanner(new File("C:/Users/James Vausch/Desktop/MaleNames.txt"));
System.out.println("");
} catch (Exception e) {
System.out.println("Could not locate the data file! Please check the address of the file.");
}
readFile();
}
public static void readFile() throws Exception{
while(readFile.hasNext()) {
names[i] = readFile.next();
System.out.println((x + 1) + ". " + names[i]);
x++;
i++;
}
checkName();
}
public static void checkName() throws Exception{
System.out.println("Enter a name so that we can check that on my database. :3");
n = new Scanner(System.in).nextLine();
for(int j = 0; j < 1362; j++){
if(n.equalsIgnoreCase(names[j])){
System.out.println("Name found on my database :>");
break;
}else{
System.out.println("Name not found on my database. :<");
System.out.println(names[1000]);
break;
}
}
System.out.println("Do you want to search for another name? Yes or No?");
String ask = new Scanner(System.in).next();
if(ask.equalsIgnoreCase("Yes")){
checkName();
}else{
closeFile();
}
}
public static void closeFile() {
readFile.close();
}
}
Here I also have sample names to be saved on a text file (MaleNames.txt):
Joshua
James
Theodore
Thewa
Adrian
It should find the String inside it's array and print
Name found on my database
The problem is here:
for(int j = 0; j < 1362; j++){
if(n.equalsIgnoreCase(names[j])){
System.out.println("Name found on my database :>");
break;
}else{
System.out.println("Name not found on my database. :<");
System.out.println(names[1000]);
break;
}
}
This code will break out of the loop at the first name that doesn't match, which is always the first name (unless you happen to enter the first name in the list).
Instead, you could check all the names and break only when you match the target name, or save yourself a lot of pain and code by just doing this instead of your loop:
if (Arrays.asList(names).contains(n)) {
System.out.println("Name found on my database :>");
} else {
System.out.println("Name not found on my database. :<");
}
Better still, use a Set<String> instead of a String[] to hold your names, in which case the test just becomes:
if (names.contains(n))
As a general rule, use collections in preference to arrays.
If this is an assignment that specifies that collections (and streams) are not to be used, you would have to do something like this:
boolean found = false;
for (int j = 0; j < names.length && !found; j++){
found = n.equalsIgnoreCase(names[j]);
}
if (found) {
System.out.println("Name found on my database :>");
} else {
System.out.println("Name not found on my database. :<");
System.out.println(names[1000]);
}
I'm writing a simple program to reformat source code using new line style curly brace to end of line curly brace style. I'm having trouble manipulating strings to then pass them to an arraylist.
My specific problem is when I find a line which has a new line curly brace, I then get the index of the line before, set the new line to the element in the previous index and append a "{", I am having trouble removing the previous line.
I've tried doing .remove(previousIndex) but it did not work
Sample input:
public class Reformat
{
public static void main(String[] args)
{
System.out.println("Test 1");
System.out.println("Test 2");
}
}
This is my code so far:
public class Reform {
public static void main(String[] arg) throws FileNotFoundException {
// Pass source file to File object
File sourceFile = new File(arg[0]);
// Create AL of type String to hold tokens
ArrayList<String> code = new ArrayList<String>();
Scanner input = null;
// Try-catch block to handle any errors while opening the file
try {
input = new Scanner(sourceFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
while (input.hasNextLine()) {
String currentLine = input.nextLine();
if (currentLine.isEmpty()) {
continue;
} else if (currentLine.contains("{") && code.size() != 0) {
int previousIndex = code.size() - 1;
code.add(code.set(previousIndex, code.get(previousIndex) + "{"));
} else {
code.add(currentLine);
}
}//end of while
for (String line : code)
System.out.println(line);
}//end of finally
input.close();
}//end of main
}//end of class
I played around with the code in question and was able to resolve by arranging in this manner:
else if (currentLine.contains("{") && code.size() != 0) {
int previousIndex = code.size() - 1;
String newLine = code.set(previousIndex, code.get(previousIndex) + "{");
code.add(previousIndex, newLine);
code.remove(previousIndex);
Not 100% sure why it worked in this way and not the other attempts. I would appreciate an explanation. The worst type of solutions are the ones you don't understand.
This is wrong:
code.add(code.set(previousIndex, code.get(previousIndex) + "{"));
It should be:
code.set(previousIndex, code.get(previousIndex) + "{");
I am unable to terminate my java program which takes some strings as input, below is the code I used to process the input
import java.util.Scanner;
public class EPALIN {
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
String p = null;
while((p=sc.nextLine())!=null)
{
System.out.println(getPalin(p));
}
sc.close();
}
public static String getPalin(String st)
{
int i =0;
int j = st.length()-1;
String res = "";
while(i<=j)
{
if(st.substring(i, i+1).equals(st.substring(j, j+1)))
{
res+=st.substring(i, i+1);
i++;
j--;
}
else
{
res+=st.substring(i,i+1);
i++;
}
}
if(res.length()%2==0)
return res+(new StringBuffer(res).reverse().toString());
else
return res+(new StringBuffer(res).reverse().toString().substring(1));
}
}
Even using
while((p=sc.nextLine())!="")
didn't work, its a problem from SPOJ problemId EPALIN
Do something like this
while(!(p=sc.nextLine()).equals("")) {
// ...
}
I try your code with the while i'm using and it's seems to work.
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
String p = null;
while(!(p=sc.nextLine()).equals(""))
{
System.out.println(getPalin(p));
}
sc.close();
}
public static String getPalin(String st)
{
int i=0;
int j=st.length()-1;
String res = "";
while(i<=j)
{
if(st.substring(i, i+1).equals(st.substring(j, j+1)))
{
res+=st.substring(i, i+1);
i++;
j--;
}
else
{
res+=st.substring(i,i+1);
i++;
}
}
if(res.length()%2==0)
return res+(new StringBuffer(res).reverse().toString());
else
return res+(new StringBuffer(res).reverse().toString().substring(1));
}
}
You should use hasNext()
String delimiter = "\r\n|\r"; //Or try System.getProperty("line.separator");
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter(delimiter);
while (scanner.hasNext()) {
String p = scanner.next();
// ...
}
}
See the Scanner documentation. Scanner.nextLine() won't return null. If the input ends (for instance, the judge has piped a file to stdin, and the file ends), it will instead throw NoSuchElementException. If it doesn't, nextLine() will block.
Ordinarily what you could do here, because the the problem description states that each test case will be on its own line is (similar to what CandiedOrange suggested):
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
...
}
However, the problem also states:
Large I/O. Be careful in certain languages.
In contest problem lingo, this means "don't use Scanner." For fast I/O, you have a couple of options, but something like the following should work fine while keeping you under the time limit:
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(
System.in));
String line;
while ((line = in.readLine()) != null)
doSomething(line); // etc
}
Note that you will most likely also have to collect all of your output and print it at the end, rather than making a bunch of System.out.println(), which have overhead that you can avoid by only printing once.
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;
}
I'm writing a program to delete duplicate consecutive words from a text file, then replaces that text file without the duplicates. I know that my current code does not handle the case where a duplicate word is at the end of one line, and at the beginning of the next line since I read each line into an ArrayList, find the duplicate, and remove it. After writing it though, I wasn't sure if this was an 'ok' way to do it since now I don't know how to write it back out. I'm not sure how I can keep track of the punctuation for beginning and end of line sentences, as well as the correct spacing, and when there are line returns in the original text file. Is there a way to handle those things (spacing, punctuation, etc) with what I have so far? Or, do I need to do a redesign? The other thing I thought I could do is return an array of what indices of words I need deleted, but then I wasn't sure if that's much better. Anyway, here is my code: (thanks in advance!)
/** Removes consecutive duplicate words from text files.
It accepts only one argument, that argument being a text file
or a directory. It finds all text files in the directory and
its subdirectories and moves duplicate words from those files
as well. It replaces the original file. */
import java.io.*;
import java.util.*;
public class RemoveDuplicates {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Program accepts one command-line argument. Exiting!");
System.exit(1);
}
File f = new File(args[0]);
if (!f.exists()) {
System.out.println("Does not exist!");
}
else if (f.isDirectory()) {
System.out.println("is directory");
}
else if (f.isFile()) {
System.out.println("is file");
String fileName = f.toString();
RemoveDuplicates dup = new RemoveDuplicates(f);
dup.showTextFile();
List<String> noDuplicates = dup.doDeleteDuplicates();
showTextFile(noDuplicates);
//writeOutputFile(fileName, noDuplicates);
}
else {
System.out.println("Shouldn't happen");
}
}
/** Reads in each line of the passed in .txt file into the lineOfWords array. */
public RemoveDuplicates(File fin) {
lineOfWords = new ArrayList<String>();
try {
BufferedReader in = new BufferedReader(new FileReader(fin));
for (String s = null; (s = in.readLine()) != null; ) {
lineOfWords.add(s);
}
}
catch (IOException e) {
e.printStackTrace();
}
}
public void showTextFile() {
for (String s : lineOfWords) {
System.out.println(s);
}
}
public static void showTextFile(List<String> list) {
for (String s : list) {
System.out.print(s);
}
}
public List<String> doDeleteDuplicates() {
List<String> noDup = new ArrayList<String>(); // List to be returned without duplicates
// go through each line and split each word into end string array
for (String s : lineOfWords) {
String endString[] = s.split("[\\s+\\p{Punct}]");
// add each word to the arraylist
for (String word : endString) {
noDup.add(word);
}
}
for (int i = 0; i < noDup.size() - 1; i++) {
if (noDup.get(i).toUpperCase().equals(noDup.get(i + 1).toUpperCase())) {
System.out.println("Removing: " + noDup.get(i+1));
noDup.remove(i + 1);
i--;
}
}
return noDup;
}
public static void writeOutputFile(String fileName, List<String> newData) {
try {
PrintWriter outputFile = new PrintWriter(new BufferedWriter(new FileWriter(fileName)));
for (String str : newData) {
outputFile.print(str + " ");
}
outputFile.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
private List<String> lineOfWords;
}
An example.txt:
Hello hello this is a test test in order
order to see if it deletes duplicates Duplicates words.
How about something like this? In this case, I assume it is case insensitive.
Pattern p = Pattern.compile("(\\w+) \\1");
String line = "Hello hello this is a test test in order\norder to see if it deletes duplicates Duplicates words.";
Matcher m = p.matcher(line.toUpperCase());
StringBuilder sb = new StringBuilder(1000);
int idx = 0;
while (m.find()) {
sb.append(line.substring(idx, m.end(1)));
idx = m.end();
}
sb.append(line.substring(idx));
System.out.println(sb.toString());
Here's the output:-
Hello this a test in order
order to see if it deletes duplicates words.