Hi guys this is my first post in this website and I'm still new to Java. This my code that i am working on.
public static void main(String[] args) throws Exception {
// debug
if ($DEBUG) System.out.println("starting\n");
//read data from text file into arrays w,p
String[] wArr = new String[50];
String[] pArr = new String[50];
String fileName = "homs.txt";
readFile(fileName, wArr, pArr);
//main control loop
while (true) {
//use input dialog to get 2 words from user
String input = JOptionPane.showInputDialog(null,"Enter two words: ");
String[] words = input.split("\\s+");
String w1 = words[0];
String w2 = words[1];
//check each word if in dictionary
int w1ix = chkFound(wArr, w1);
boolean isFound = (w1ix >= 0);
System.out.println(w1 + " is found: " + isFound);
int w2ix = chkFound(wArr, w2);
boolean isFound2 = (w2ix >= 0);
System.out.println(w2 + " is found: " + isFound2);
if (w1ix >=0 && w2ix >=0 ) msg = "both words " + w1 + " and " + w2 +
"\n\tare in dictionary";
else { msg = "one or more words not in dictionary: ";
if (w1ix <0) msg += w1 + " ";
if (w2ix <0) msg += w2 + " ";
System.out.println(msg);
//check if homonyms
boolean isHom = chkHom(pArr, w1, w2);
//output result
String line = msg +
"\nWord 1: " + w1 +
"\nWord 2: " + w2 +
"\nWord 1 in dictionary: " + isFound +
"\nWord 2 in dictionary: " + isFound2 +
"\nHomonyms: " + isHom;
JOptionPane.showMessageDialog(null, line);
//ask user to continue Y/N?
int cont = JOptionPane.showConfirmDialog(null, "Continue?");
if (cont > 0)
break;//exit loop or continue
}
//end main
}
}
public static int chkFound(String[] wArr, String w) {
for (String a : wArr) {
if(a.equals(w))
return 1;
}
return -1;
}//end chkFound
My problem for this code is that when i run it it keeps looping
String input = JOptionPane.showInputDialog(null,"Enter two words: ");
I think the reason for this problem is this part of the code. I have not come up with a solution for this though.
public static int chkFound(String[] wArr, String w) {
for (String a : wArr) {
if(a.equals(w))
return 1;
}
return -1;
}//end chkFound
https://docs.oracle.com/javase/7/docs/api/constant-values.html#javax.swing.JOptionPane.OK_OPTION
public static final int OK_OPTION 0
your break doesn't work
if (cont > 0)
break;//exit loop or continue
change it to:
final int cont = JOptionPane.showConfirmDialog(null, "Continue?","Continue?", JOptionPane.YES_NO_OPTION);
if(cont == JOptionPane.NO_OPTION){
break;
}
Related
I am trying to figure out how to make a grep method that can read wrapped phrases from up-to infinity lines(That is a sentence or string spanning multiple lines of a given text file) in java. Here is my current code for the grep function:
public static void grep() throws IOException{
BufferedReader f = new BufferedReader(new FileReader("Cabbages.txt"));
Scanner in = new Scanner(System.in);
String line = "", input = "", wrappedPhrase = "", modified = "";
int c = 0, foundCount = 0;
boolean found = false;
System.out.print("Please enter something you want to grep: ");
input = in.nextLine();
while((line = f.readLine()) != null) {
c++;
found = false;
int index = line.indexOf(input);
while(index >= 0) {
modified = "<" + line.substring(line.indexOf(input), (line.indexOf(input)+input.length())) + ">";
found = true;
index = line.indexOf(input, index + 1);
foundCount++;
}
if(found) {
System.out.println("Found on line: " + c + ", which is: " + line.replace(input, modified));
}
}
if(foundCount <= 0) {
System.out.println("Sorry, the input string of: \"" + input + "\" was not found within the given file.");
}else {
System.out.println("In total, the input string of: \"" + input + "\"" + " was found " + foundCount + " time(s).");
}
}
I am trying to write a program that asks the user for a letter (R,G,B) and then after five output the result. There cannot be 2 letters in a row. I get indexoutofbounds when I enter the third letter and the double letter check does not work.
package absolutejava;
import java.util.Scanner;
import java.util.*;
public class RGB {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int count = 0;
boolean isColor = false;
String finalString = "";
int i = 0;
int j = 1;
String temp = "";
for (count = 0; count < 5;) {
System.out.println("Enter a color. Use R for red, G for green, and B for blue.");
temp = kb.nextLine();
if ((temp.equals("R") || temp.equals("G") || temp.equals("B"))) {
isColor = true;
temp += temp;
} else {
isColor = false;
System.out.println("Invald Color, please choose again");
}
if (isColor == true && j < 6 && i < 5) {
count++;
if (temp.length() > 2 && temp.length() <= 5 && finalString.substring(i, j).equals(temp.substring(i - 1, j - 1))) {
System.out.println("Two colors cannot be next to each other ");
isColor = false;
count--;
} else if (temp.length() == 5) {
finalString = finalString + temp.substring(i);
//debugging line
System.out.println("i " + i + "j " + j + "count " + count + " " + finalString + " length " + temp.length());
i++;
j++;
} else {
finalString = finalString + temp.substring(i, j);
//debugging line
System.out.println("i " + i + "j " + j + "count " + count + " " + finalString + " length " + temp.length());
i++;
j++;
}
}
}
System.out.println(finalString);
}
}
The following line is definitely wrong:
temp += temp;
You're replacing temp with the current input every iteration, so this will have no effect. Even if that wasn't the case, you'd just be adding the same string to itself - e.g. "A" would become "AA."
I assume you meant
finalString += temp;
or something to that effect.
In general, it seems like you're mixing up temp and final in a few places.
One more thing: don't explicitly compare to true and false, it's unnecessary and is generally considered poor style.
This is my Android Java code . I don't understand why it is not working like java code . it is example of prime number . Suppose we want to find prime number between 1 to 5 . So I expect the result 2, 3, 5 . But I only got the result 5 . In my Java code I got the correct result . I mean 2, 3, 5 . Please help me figure out this problem.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prime);
Button btn = (Button)this.findViewById(R.id.click_btn);
btn.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
TextView resp = (TextView) findViewById(R.id.response);
// Get number from EditText
EditText startnumber = (EditText) findViewById(R.id.first_number);
EditText endnumber = (EditText) findViewById(R.id.second_number);
// get the Strings from the EditTexts
String number1 = startnumber.getText().toString();
String number2 = endnumber.getText().toString();
// Convert Strings to int
int x1number = Integer.parseInt(number1);
int x2number = Integer.parseInt(number2);
String str = "List of prime numbers between " + x1number + " and " + x1number + ": ";
//resp.setText(str);
for(int i = x1number; i <= x2number; i++){
if(isPrime(i)){
resp.setText( str + String.valueOf(i));
}
}
}
});
}
public static boolean isPrime(int n){
if( n <= 1) {
return false;
}
for( int i = 2; i <= n/2; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
Here is my Java code .
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package primenumberstwo;
import java.util.Scanner;
/**
*
* #author vubon
*/
public class PrimeNumberstwo {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner s = new Scanner(System.in);
System.out.println("Enter your first number: ");
int start = s.nextInt();
System.out.println("Enter your second number: ");
int end = s.nextInt();
System.out.println("List of prime numbers bettween " + start + " and " + end);
for(int i = start; i <= end; i++){
if(isPrime(i)){
System.out.println(String.valueOf(i));
}
}
}
public static boolean isPrime(int n){
if( n <= 1) {
return false;
}
for( int i = 2; i <= n/2; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
You are overwriting the content of the TextView resp in each iteration that's why you see just le last one.
Try something like this:
String str = "List of prime numbers between " + x1number + " and " + x1number + ": ";
String result = "";
for(int i = x1number; i <= x2number; i++){
if(isPrime(i)){
result = result + " " + i;
}
}
if(!("".equalsIgnoreCase(result.trim()))){
resp.setText(str + result);
}
Problem is not in Android SDK. your logic is wrong.
String str = "List of prime numbers between " + x1number + " and " + x1number + ": ";
//resp.setText(str);
for(int i = x1number; i <= x2number; i++){
if(isPrime(i)){
resp.setText( str += String.valueOf(i));//see change here
}
}
Try with:
str = str + String.valueOf(i);
resp.setText(str);
you have found all prime numbers but override with last one on last loop iterate.
Try that;
String str = "List of prime numbers between " + x1number + " and " + x1number + ": ";
resp.setText(str);
for(int i = x1number; i <= x2number; i++){
if(isPrime(i)){
resp.setText( resp.getText() + String.valueOf(i));
}
}
Ok, so I really didn't know how to say it right for the title so this should shed some light on the situation.
I'm making a palindrome program in Java. In every which way you look at it, it works just fine. It reads in a file using Scanner, searches through the entire file and outputs if that line in the text file is a palindrome. If you have any special characters or caps it deletes them and turns everything to lowercase.
My issue is that after the check is done on each line, I want to show some extra information next to the result.
Each line should show how many words are in the line, how many characters and if its a palindrome or not.
Anyway here is the code, hopefully someone can help me figure this out. Thanks.
import java.io.File;
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
//Global Variables
Scanner cScan = null;
Scanner wScan = null;
Scanner pScan = null;
int charCount = 0, numLines = 0, numChars = 0, wordCount = 0;
//Take in User Input
Scanner iScan = new Scanner(System.in); //Start input Scanner
String fileName = null;
System.out.print("Please Enter a File Name: ");
fileName = iScan.nextLine();
iScan.close(); //Close input Scanner
//Read File Specified by User
File palin = new File(fileName);
try {
//Checks for Number of Characters
cScan = new Scanner(palin);
while(cScan.hasNextLine()) {
String line = cScan.nextLine();
numChars += line.length();
numLines++;
}
//Checks for Number of Words
wScan = new Scanner(palin);
while (wScan.hasNext()) {
wScan.next();
wordCount++;
}
//Format Lines
pScan = new Scanner(palin);
while (pScan.hasNext()) {
String line = pScan.nextLine();
String reString = line.replaceAll("[^\\p{L}\\p{Nd}]", "");
String lString = reString.toLowerCase();
boolean pali = false;
String tP = "Yes", fP = "No";
int n = lString.length();
for (int i = 0; i < (n / 2) + 1; ++i) {
if (lString.charAt(i) != lString.charAt(n - i - 1)) {
pali = false;
break;
}
else if (lString.charAt(i) == lString.charAt(n - i - 1)) {
pali = true;
break;
}
}
if (pali == true)
System.out.println(line + " w: " + wordCount + ", " + " c: " + charCount + ", " + tP);
else
System.out.println(line + " w: " + wordCount + ", " + " c: " + charCount + ", " + fP);
}
}
catch(Exception e) {
System.out.println("File Could Not be Found");
}
//charCount = (numLines + numChars) - 1; //Minus 1 to Compensate for EOL at EOF
//System.out.println(charCount);
//System.out.println(wordCount);
//System.out.println(spRemover);
}
}
I cleaned up your code a little bit.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Palindrome {
int charCount = 0;
int totalWordCount = 0;
public static String isPalindrome(String str) {
if(str.equals(new StringBuffer().append(str).reverse().toString())) {
return "a";
}
else {
return "not a";
}
}
public static int getNumberOfWords(String str) {
return str.isEmpty() ? 0 : str.split("\\s+").length;
}
public void process(File file) {
try {
Scanner sc = new Scanner(file);
int i = 0;
while(sc.hasNextLine()) {
i++;
String line = sc.nextLine();
int wordCount = getNumberOfWords(line);
System.out.println("Line " + i + "is " + isPalindrome(line) + " palindrome. It has " + wordCount + " words and " + line.length() + " characters.");
charCount = charCount + line.length();
totalWordCount = totalWordCount + wordCount;
}
sc.close();
System.out.println("There are " + i + " lines in the file with a total of " + totalWordCount + " words and " + charCount + " characters.");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Scanner iScan = new Scanner(System.in);
String fileName = null;
System.out.print("Please Enter a File Name: ");
fileName = iScan.nextLine();
iScan.close();
File file = new File(fileName);
Palindrome pal = new Palindrome();
pal.process(file);
}
}
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
public class IteratingFileWithInformation {
int charCount = 0 ;
int totalWordCount = 0;
private static String checkPalindrome(String line) {
return line.equals(new StringBuffer().append(line).reverse().toString()) ? "a" : "not a" ;
}
private static int getNumberOfWords(String words) {
return words.isEmpty() ? 0 : words.split("\\s+").length;
}
private void checkFileAndProcess(BufferedReader file) {
Scanner input = new Scanner(file);
int i = 0;
while(input.hasNextLine()) {
i++;
String line = input.nextLine();
int wordCount = getNumberOfWords(line);
System.out.println("Line: " + i + " is " + checkPalindrome(line) + " Palindrome. It has " + wordCount + " words and " + line.length() +
" characters. ");
charCount += line.length();
totalWordCount += wordCount;
}
input.close();
System.out.println("There are " + i + " lines in the file with a total of " + totalWordCount + " words and " + charCount + " characters.");
}
public static void main(String[] args) throws FileNotFoundException {
Scanner givefileName = new Scanner(System.in);
String fileName = null;
System.out.println("Enter the file name :");
fileName = givefileName.nextLine();
givefileName.close();
FileReader file = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(file);
IteratingFileWithInformation fileWithInformation = new IteratingFileWithInformation();
fileWithInformation.checkFileAndProcess(bufferedReader);
}
}
I have a task:
"Send integers n [1 .. 10] from command line. Enter n rows to the Console, find the shortest and the longest line. Print the results and line length."
My idea is: Create array of strings and copy every line from BufferedReader to the array data[i]. Sample of my code:
String[] data = new String[n];
int j=0;
for (int i = 1; i <= n; i++) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please, enter " + i + " string: ");
String line = in.readLine();
for (int j=0; j<=data.length;j++){
data[j] = line;
j++;
} ///:~
System.out.println("Your " + i + " string : " + data[j] + "String len: " + line.length());
} ///:~
But I could not find the way how to fill elements of array data[i] with new line from console.
Can you please give me a small hint?
To fill data, just replace the inner for-loop with a simple assignment using index i-1:
for (int i = 1; i <= n; i++) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please, enter " + i + " string: ");
String line = in.readLine();
data[i-1] = line;
System.out.println("Your " + i + " string : " + data[i-1] + "\nString len: " + line.length());
}
I left the loop from 1 to n instead of 0 to n-1 because you're printing i.
But if you only want the shortest and longest lines, there's no need to store all the lines, you only need to check the length of the current line against the length of the shortest and longest lines and change them appropriately.
the easyst way is
data[i-1] = in.readLine();
Thank you all for all your Help :)
Here is my example:
package taskstring;
import java.io.*;
public class TaskString {
public static void main(String[] args) throws java.lang.Exception {
int n = Integer.parseInt(args[0]);
if (n <= 0) {
System.out.println("Wrong! please send more numbers to java");
return;
}
System.out.println("Enjoy! You are going to send " + n + " string(s) to java");
int maxLen = 0;
int minLen = 0;
for (int i = 1; i <= n; i++) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please, enter " + i + " string: ");
String line = in.readLine();
System.out.println("Your " + i + " string : " + "String len: " + line.length());
if (maxLen < line.length()) {
System.out.println("New string is bigger");
maxLen = line.length();
} else {
System.out.println("New string is smaller");
}
if (minLen > line.length() || minLen == 0) {
System.out.println("New string is smaller" + " minLen=" + minLen);
minLen = line.length();
} else {
System.out.println("New string is bigger");
}
//return;
} ///:~
System.out.println("Max row: " + maxLen + "\nMin row: " + minLen);
} ///:~
}