so I have being doing this program to verify if the word "bob" is in a string that the user enters. Example: "asddbobasd" -> "here is bob". Also, if there is one character between the bs it should print out "here is bob". Otherwise, it should print "here isn't bob".
tl dr: bxb = here is bob .bob = here is bob. bok = here isn't bob. When I'm executing the program, netbeans throws me an (!) at the if statement of (yed=='b' && zed=='b')
package lab;
import java.util.Scanner;
public class Lab {
public static void main(String[] args) {
char yed,zed;
Scanner sc = new Scanner (System.in);
String x;
System.out.println("Word");
x = sc.nextLine().toLowerCase();
int m=0;
for (int i = 0; i<=x.length(); i++) {
yed = x.charAt(i);
int j=i+2;
zed = x.charAt(j);
if (yed=='b' && zed=='b')
m++;
}
if (m>0){
System.out.println("here is bob");
}
if (m==0) {
System.out.println("here isn't bob");
}
}
}
Try to replace this:
for (int i = 0; i<=x.length(); i++) {
With using i<x.length()-2 instead of i<=x.length():
for (int i = 0; i<x.length()-2; i++) {
Related
i'am new injava , in this problem i will insert a numbers of strings in a array , but the compiler give me this probleme :
PhoneNumber.java:29: error: incompatible types: String cannot be converted to boolean
while(test[i][j])
^
1 error
public class PhoneNumber{
public static void check_number(String[][] numbers, int n)
{
int i,j;
for(i = 0; i < n; i++)
{
for(j = 0; j < numbers[i].length; j++)
{
if(numbers[i][j] == "4" || numbers[i][j] == "5")
{
System.out.println("Done");
}
}
}
}
public static void main(String[] args)
{
String[][] test = new String[100][100];
Scanner number = new Scanner(System.in);
int n,i,j;
System.out.println("enter the number of numbers");
n = number.nextInt();
for(i = 0 ; i < n; i++)
{
System.out.println("enter the number " + i + 1);
j = 0;
while(test[i][j])
{
test[i][j] = number.nextLine();
j++;
}
}
check_number(test,n);
}
}
Here's the basic approach for a 1D String array with notes included:
import java.util.Scanner;
public class PhoneNumber{
public static void check_number(String[] numbers, int n)
{
for(int i = 0; i < n; i++)
{
System.out.println(numbers[i]);
//the String class method equals is best for comparison:
if(numbers[i].equals("4") || numbers[i].equals("5"))
{
System.out.println("Done");
}
}
}
public static void main(String[] args)
{
Scanner number = new Scanner(System.in);
int n;
System.out.println("enter the number of numbers");
n = number.nextInt();
//clean the scanner buffer after input especially with Int -> Line
number.nextLine();
//size your array after getting user input
String[] test = new String[n];
for(int i = 0 ; i < n; i++)
{
//parenthesis needed to get correct output for i + 1
System.out.println("enter the number " + (i + 1));
test[i] = number.nextLine();
}
check_number(test,n);
}
}
I am currently attempting to make a Palindrome Checker using a series of Clean and dirty arrays and while I've gotten it to compile but I'm having issues getting the code to detect the actual palindromes
Below is the code in question, any and all help would be most appreciated.
import java.io.*;
import java.util.Scanner;
public class palindrome
{
public static void main (String[] args) throws IOException
{
File inputFile = new File ("Palindromes.txt");
Scanner inputScan = new Scanner (inputFile);
String [] dirty = new String [20];
int i = 0;
while (inputScan.hasNext())
{
dirty[i] = inputScan.nextLine();
System.out.println(dirty[i]);
i++;
}
inputScan.close();
String [] clean = new String [i];
String reverse ="";
for (int x = 0; x < clean.length; x++)
{
clean[x] = "";
for (int z = length; z < dirty[x].length(); z--)
{
char test = dirty[x].charAt(z);
if (Character.isLetterOrDigit(test))
{
test = Character.toLowerCase(test);
clean [x] += test;
if (clean[x].equals(clean[z]))
{
System.out.println(clean[z] +" is a palindrome");
} else
{
System.out.println(clean[z] +" is NOT a palindrome");
}
}
}
}
for (int j = 0; j < clean.length; j++)
{
System.out.println(clean[j]);
}
}
Are you trying to do something like this?
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Palindrome {
public static boolean isPalindrome(String s) {
s = s.toLowerCase().replaceAll("[\\s\\p{Punct}]", "");
int len = s.length(), mid = len / 2;
for (int x = 0; x < mid; x++)
if (s.charAt(x) != s.charAt(len - x - 1))
return false;
return true;
}
public static void main(String[] args) throws IOException {
File inputFile = new File("Palindromes.txt");
try (Scanner scanner = new Scanner(inputFile)) {
while (scanner.hasNextLine()) {
String s = scanner.nextLine();
if (isPalindrome(s)) {
System.out.println(s + " is a palindrome");
} else {
System.out.println(s + " is NOT a palindrome");
}
}
}
}
}
I've made a 12 by 12 table that runs in the same program, but i'd like to make it OO so that i can put the "public static void main" in another "testfile" and it will still run properly..i'm having some problems with the OO approach and i really need help...This is what my code looks like:
import java.util.Scanner;
import java.util.Arrays;
import java.util.Random;
public class PlayingArea {
public static void main(String[] args) {
Random r = new Random();
Scanner input = new Scanner(System.in);
System.out.println("How many regions would you like (2- 4)");
int region = input.nextInt();
String letters = "";
while(letters.length() < 2) {
if (region == 4) {
letters= "EFGH";
}
if (region == 3) {
letters= "EFG";
} else if (region == 2) {
letters= "EF";
} else if (region < 2) {
System.out.println("You inputed a wrong value, try again...");
}
}
int N = letters.length();
char [][] letter = new char[12][12];
for (int j = 0; j < letter.length; j++) {
for(int i=0; i < letter.length; i++) {
letter[i][j] = letters.charAt(r.nextInt(N)) ;
}
}
for (char[] letterRow : letter)
System.out.println(Arrays.toString(letterRow));
}
}
if you're relatively new to java then you're doing quite well. Be aware there is an infinite loop in your program (fixed below) if you enter a number outside of 2-4.
Firstly, your class PlayingArea needs some member variables to represent state.
The first one is the String letters (EF or EFG or EFGH), which is initialized via a constructor in the code below.
The second one is the char[][] grid (renamed from letter in your code) which is assigned a value in the populate() method, which puts letters into the grid.
The other method, gridAsString() does just that.
The public static void main can easily now be moved to another class, if you like.
Have fun.
public class PlayingArea {
private String letters;
private char[][] grid;
public PlayingArea(String letters) {
this.letters = letters;
}
public void populate() {
int n = letters.length();
grid = new char[12][12];
Random r = new Random();
for (int j = 0; j < grid.length; j++) {
for (int i = 0; i < grid.length; i++) {
grid[i][j] = letters.charAt(r.nextInt(n));
}
}
}
public String gridAsString() {
StringBuilder sb = new StringBuilder();
for (char[] letterRow : grid) {
sb.append(Arrays.toString(letterRow)).append('\n');
}
return sb.toString();
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many regions would you like (2- 4)");
String letters = "";
while (letters.length() < 2) {
int region = input.nextInt();
if (region == 4) {
letters = "EFGH";
} else if (region == 3) {
letters = "EFG";
} else if (region == 2) {
letters = "EF";
} else {
System.out.println("You inputed a wrong value, try again...");
}
}
PlayingArea playingArea = new PlayingArea(letters);
playingArea.populate();
System.out.println(playingArea.gridAsString());
}
}
Okay so I know there are other Morse code answers out there, but I have looked at many, but none of them worked. For my assignment I was to read a file, Morse.txt, into parallel arrays. Instead I just made two files, Morse.txt and Alphabet.txt one with code and the other with numbers and alphabet. I am supposed to use a class I made to do the translating part and when called in main it should translate user input. I can't seem to get this working. I've tried so many things from using a toString in the class or getter, but the return is not found when I put in the loop which I think has to be there(if that makes sense)..anyway here is my code for main:
import java.util.*;
import java.util.Scanner;
import java.io.*;
public class redo
{
public static void main(String[]args) throws IOException
{
String line2, file2 = "Morse.txt";
String line, file = "Alphabet.txt";
File openFile = new File(file);
File openFile2 = new File(file2);
Scanner inFile = new Scanner(openFile);
Scanner inFile2 = new Scanner(openFile2);
int index = 36;
char[] charArray = new char[index];
String[] code = new String[index];
for(index = 0; index < 36; index++)
{
while(inFile.hasNext())
{
line = inFile.nextLine();
charArray = line.toCharArray();
//System.out.println(charArray[index]);
}
}
for(index = 0; index < 36; index++)
{
while(inFile2.hasNext())
{
code[index] = inFile2.nextLine();
//System.out.println(code[index]);
}
}
Scanner keyboard = new Scanner(System.in);
String userInput;
System.out.println("Enter something to translate: ");
userInput= keyboard.nextLine();
Translate inputTranslate = new Translate(userInput);
inputTranslate.setInput(userInput);
inputTranslate.setAlph(charArray);
inputTranslate.setCode(code);
inFile.close();
}
}
and here is my class Translate(some things are commented out):
public class Translate
{
String input;
String code[];
char alph[];
public Translate(String input)
{
this.input = input;
}
public void setInput(String input)
{
this.input = input;
}
public void setAlph(char[] alph)
{
this.alph = alph;
}
public void setCode(String[] code)
{
this.code = code;
}
public String getInput()
{
return input;
}
// public String getTranslate()
// {
// for(int i = 0; i < input.length(); i++)
// {
// for(int index = 0; index < alph.length; index++)
// {
// if(input.charAt(i) == alph[index])
// {
// String output = code[index];
// }
// }
// }
// return output;
// }
}
Morse.txt:
.----
..---
...--
....-
.....
-....
--...
---..
----.
.-
-...
-.-.
-..
.
..-.
--.
....
..
.---
-.-
.-..
-.
.--.
--.-
.-.
...
..-
...-
.--
-..-
-.--
--..
Alphabet.txt:
1
2
3
4
5
6
7
8
9
0
A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z
The problem is your return can't reach "output", you need to declare "output" above the loops and initialise it to output = null;
Even then it'll only send one string. So I did this;
public String getTranslate()
{
String output = null;
String[] translated = new String[input.length()];
for(int i = 0; i < input.length(); i++)
{
for(int index = 0; index < alph.length; index++)
{
if(input.charAt(i) == alph[index])
{
output = code[index];
translated[i] = output;
}
}
}
for (int j = 1; j < translated.length; j++) {
output = translated[0].concat(translated[j]);
}
return output;
}
This basically sticks all the codes together giving you your desired outcome.
This question already has an answer here:
Closed 10 years ago.
I run through the entire code. I am able to enter a simple .txt file to search for a word. After it asks for a word, it returns
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -48
at SearchEngine.main(SearchEngine.java:150)
Line 150 is for (int j = 0; j
Any help debugging?
This is basic search engine program that should be able to search a .txt file for any word.
Assignment link: http://cis-linux1.temple.edu/~yates/cis1068/sp12/homeworks/concordance/concordance.html
import java.util.*;
import java.io.*;
public class SearchEngine {
public static int getNumberOfWords (File f) throws FileNotFoundException {
int numWords = 0;
Scanner scan = new Scanner(f);
while (scan.hasNext()) {
numWords++;
scan.next();
}
scan.close();
return numWords;
}
public static void readInWords (File input, String [] x) throws FileNotFoundException {
Scanner scan = new Scanner(input);
int i = 0;
while (scan.hasNext() && i<x.length) {
x[i] = scan.next();
i++;
}
scan.close();
}
public static int getNumOfDistinctWords (File input, String [] x) throws FileNotFoundException {
Scanner scan = new Scanner(input);
int count = 0;
int i = 1;
while (scan.hasNext() && i<x.length) {
if (!x[i].equals(x[i-1])) {
count++;
}
i++;
}
scan.close();
return count;
}
public static void readInDistinctWords (String [] x, String [] y) {
int i = 1;
int k = 0;
while (i<x.length) {
if (!x[i].equals(x[i-1])) {
y[k] = x[i];
k++;
}
i++;
}
}
public static int getNumberOfLines (File input) throws FileNotFoundException {
int numLines = 0;
Scanner scan = new Scanner(input);
while (scan.hasNextLine()) {
numLines++;
scan.nextLine();
}
scan.close();
return numLines;
}
public static void readInLines (File input, String [] x) throws FileNotFoundException {
Scanner scan = new Scanner(input);
int i = 0;
while (scan.hasNextLine() && i<x.length) {
x[i] = scan.nextLine();
i++;
}
scan.close();
}
public static void main(String [] args) {
try {
//gets file name
System.out.println("Enter the name of the text file you wish to search");
Scanner kb = new Scanner(System.in);
String fileName = kb.nextLine();
String TXT = ".txt";
if (!fileName.endsWith(TXT)) {
fileName = fileName.concat(TXT);
}
File input = new File(fileName);
//First part of creating index
System.out.println("Creating vocabArray");
int NUM_WORDS = getNumberOfWords(input);
//System.out.println(NUM_WORDS);
String [] wordArray = new String[NUM_WORDS];
readInWords(input, wordArray);
Arrays.sort(wordArray);
int NUM_DISTINCT_WORDS = getNumOfDistinctWords(input, wordArray);
String [] vocabArray = new String[NUM_DISTINCT_WORDS];
readInDistinctWords(wordArray, vocabArray);
System.out.println("Finished creating vocabArray");
System.out.println("Creating concordanceArray");
int NUM_LINES = getNumberOfLines(input);
String [] concordanceArray = new String[NUM_LINES];
readInLines(input, concordanceArray);
System.out.println("Finished creating concordanceArray");
System.out.println("Creating invertedIndex");
int [][] invertedIndex = new int[NUM_DISTINCT_WORDS][10];
int [] wordCountArray = new int[NUM_DISTINCT_WORDS];
int lineNum = 0;
while (lineNum<concordanceArray.length) {
Scanner scan = new Scanner(concordanceArray[lineNum]);
while (scan.hasNext()) {
int wordPos = Arrays.binarySearch(vocabArray, scan.next());
wordCountArray[wordPos]+=1;
for(int i = 0; i < invertedIndex.length; i++) {
for(int j = 0; j < invertedIndex[i].length; j++) {
if (invertedIndex[i][j] == 0) {
invertedIndex[i][j] = lineNum;
break;
} } }
}
lineNum++;
}
System.out.println("Finished creating invertedIndex");
}
System.out.println("Enter a word to be searched (type quit to exit program)");
Scanner keyboard = new Scanner(System.in);
String searchWord = keyboard.next();
while (!searchWord.equals("quit")) {
int counter = 0;
int wordPos = Arrays.binarySearch(allWordsArray, searchWord);
for (int j = 0; j<invertedIndex[wordPos].length; j++) {
if(invertedIndex[wordPos][j] != 0) {
int number = invertedIndex[wordPos][j];
String printOut = concordanceArray[number];
System.out.print(number);
System.out.print(" :");
System.out.println(printOut);
}
}
}
catch (FileNotFoundException exception) {
System.out.println("File Not Found");
}
} //main
} //class
From what I can see your getNumOfDistinctWords(String[] x) is wrong. This is returning a value of one less than it should be. Here is a modified version of the code:
import java.util.*;
import java.io.*;
public class SearchEngine {
//Counts the number of words in the file
public static int getNumberOfWords (File f) throws FileNotFoundException {
int numWords = 0;
Scanner scan = new Scanner(f);
while (scan.hasNext()) {
numWords++;
scan.next();
}
scan.close();
return numWords;
}
public static void readInWords (File input, String[] x) throws FileNotFoundException {
Scanner scan = new Scanner(input);
int i = 0;
while (scan.hasNext() && i < x.length) {
x[i] = scan.next();
i++;
}
scan.close();
}
public static String[] getNumOfDistinctWords (String[] x) throws FileNotFoundException {
HashSet<String> distinctWords = new HashSet<String>();
for(int i=0; i<x.length; i++){
distinctWords.add(x[i]);
}
String[] distinctWordsArray = new String[distinctWords.size()];
int i = 0;
for(String word : distinctWords){
distinctWordsArray[i] = word;
i++;
}
return distinctWordsArray;
}
public static int getNumberOfLines (File input) throws FileNotFoundException {
int numLines = 0;
Scanner scan = new Scanner(input);
while (scan.hasNextLine()) {
numLines++;
scan.nextLine();
}
scan.close();
return numLines;
}
public static void readInLines (File input, String [] x) throws FileNotFoundException {
Scanner scan = new Scanner(input);
int i = 0;
while (scan.hasNextLine() && i<x.length) {
x[i] = scan.nextLine();
i++;
}
scan.close();
}
public static void main(String [] args) {
try {
//gets file name
System.out.println("Enter the name of the text file you wish to search");
Scanner kb = new Scanner(System.in);
String fileName = kb.nextLine();
String TXT = ".txt";
if (!fileName.endsWith(TXT)) {
fileName = fileName.concat(TXT);
}
File input = new File(fileName);
//First part of creating index
System.out.println("Creating vocabArray");
int NUM_WORDS = getNumberOfWords(input);
//Output the number of words in the file
System.out.println("Number of words is: " + NUM_WORDS);
String[] allWordsArray = new String[NUM_WORDS];
readInWords(input, allWordsArray);
Arrays.sort(allWordsArray);
String[] distinctWordsArray = getNumOfDistinctWords(allWordsArray);
//Output the number of distinct words
System.out.println("Number of distinct words is: " + distinctWordsArray.length);
System.out.println("Finished creating distinctWordsArray");
System.out.println("Creating concordanceArray");
int NUM_LINES = getNumberOfLines(input);
String[] concordanceArray = new String[NUM_LINES];
readInLines(input, concordanceArray);
System.out.println("Finished creating concordanceArray");
System.out.println("Creating invertedIndex");
int [][] invertedIndex = new int[distinctWordsArray.length][10];
int [] wordCountArray = new int[distinctWordsArray.length];
int lineNum = 0;
while (lineNum < concordanceArray.length) {
Scanner scan = new Scanner(concordanceArray[lineNum]);
while (scan.hasNext()) {
//Find the position the word appears on the line, if word not found returns a number less than 0
int wordPos = Arrays.binarySearch(distinctWordsArray, scan.next());
if(wordPos > -1){
wordCountArray[wordPos] += 1;
}
for(int i = 0; i < invertedIndex.length; i++) {
for(int j = 0; j < invertedIndex[i].length; j++) {
if (invertedIndex[i][j] == 0) {
invertedIndex[i][j] = lineNum;
break;
} } }
}
lineNum++;
}
System.out.println("Finished creating invertedIndex");
}
catch (FileNotFoundException exception) {
System.out.println("File Not Found");
}
} //main
} //class
I should also point out the fact that Arrays.binarySearch(distinctWordsArray, scan.next()); will return a number less than 0 if the word is not found on that line. This is why you are getting the Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 as wordCountArray is being referenced at index -1 which of course doesn't exist!
The code after this also looks buggy but I'll let you fix that!!
Without knowing exactly where line 126 is, finding this specific bug is just too much hassle. But I've got some advice for the rest of the code:
int NUM_DISTINCT_WORDS = getNumOfDistinctWords(input, wordArray);
Normally, variables in all-caps are constants that are assigned at compile time. It's a tradition that comes from C days, when it was wonderful to know which "variables" were actually replaced by the preprocessor. But the convention has proven to be useful in other languages, and most programmers would expect NUM_DISTINCT_WORDS to be assigned a specific value at compile time.
This code is simply unreadable:
for(int i = 0; i < invertedIndex.length; i++) {
for(int j = 0; j < invertedIndex[i].length; j++) {
if (invertedIndex[i][j] == 0) {
invertedIndex[i][j] = lineNum;
break;
} } }
A more idiomatic way to show these nested loops is:
for (int i = 0; i < invertedIndex.length; i++) {
for (int j = 0; j < invertedIndex[i].length; j++) {
if (invertedIndex[i][j] == 0) {
invertedIndex[i][j] = lineNum;
break;
}
}
}
Because I use the standard Lindent script to do re-indenting, I get tabs. You don't have to use tabs, but they are convenient to add and delete with a single keystroke, and they are deep enough to be obviously visible even with smallish type faces. You'll find your code far easier to work with if you follow the standard indenting idioms.
The following piece of code is extremely unfortunate:
catch(FileNotFoundException exception) {
System.out.println("File Not Found");
}
It would be better to catch a higher-level exception and include the exception message. You can more easily handle dozens of errors if you catch an exception higher in the hierarchy, and the error messages will be far more informative.
Your main() method performs a lot of detailed work. I think your code would be easier to test, easier to debug, and easier to read, if you break it apart into more methods. Try to get the main() to read practically like a high-level description of your code.
With the line with the bug on it now easily visible, I can spot the problem:
int wordPos = Arrays.binarySearch(vocabArray, scan.next());
wordCountArray[wordPos]+=1;
You've looked up the wordPos in the vocabArray, but modified content in the wordCountArray. Are you sure they are the same size and have the same meanings?