I have written Java code that finds the no.of words in the table.
It is working within the loop, but the value becomes 0 once it exits the loop.
Please help me to get correct value.
int f=0;
int fc=0;
Statement sta4=connection.createStatement();
ResultSet rs4=sta4.executeQuery("select * from db1");
while(rs4.next())
{
word[f]=rs4.getString(1).replace("$", "");
System.out.println(" sentece ="+word[f]);
fc= countWords(word[f]);
System.out.println("The sentence has "+ fc + " words");
f++;
}
System.out.println(" count =" + fc);
int f=0;
int fc=0;
Statement sta4=connection.createStatement();
ResultSet rs4=sta4.executeQuery("select * from db1");
while(rs4.next())
{
word[f]=rs4.getString(1).replace("$", "");
System.out.println(" sentece ="+word[f]);
int fcTemp= countWords(word[f]);
System.out.println("The sentence has "+ fcTemp + " words");
fc += fcTemp;
f++;
}
System.out.println(" count =" + fc);
Use this. you werent adding up fc
Related
I want to display the sum of two numbers beside the equal sign.
Scanner scan = new Scanner(System.in);
int i ;
System.out.println("enter a number: " );
i = scan.nextInt();
int a = i - 1 ;
while(a >= 1){
System.out.println(i +" + "+ a + " = " );
//i want to display the sum of two numbers beside the equal sign.
i =i + a ;
System.out.println(i);
a --;
// how can I display the answer beside the equal sign?
}
}
}
How can I display the answer beside the equal sign?
Change your first println to print.
As per your question I think you are most probably asking how we can show the sum of two numbers in the print statement.
So in your code after "=" you just need to add (i+a) this will sum the value of i and a.
System.out.println(i +" + "+ a + " = " + (i+a)).
I hope this answers your question.
System.out.println() method prints a "newline character" (\n) right after its' input.
There is another method that does not do this:
System.out.print()
You should change
System.out.println(i +" + "+ a + " = " ); to
System.out.print(i +" + "+ a + " = " ); this.
for(int counter = 0; counter < args.length; counter++){
System.out.println("Displaying per words: " + args[counter]);
splitWords = args[counter].toCharArray();
for(int counter2 = 0; counter2 < splitWords.length; counter2++){
System.out.println("Word spliced: " + splitWords[counter2]);
System.out.println("The number equivalent of " + splitWords[counter2] + " is "
+ (int) splitWords[counter2]);
occurenceCount[(int)splitWords[counter2]]++;
System.out.println("The letter " + splitWords[counter2] +
" was shown " + occurenceCount[(int)splitWords[counter2]] + " times.");
}
}
My function doesn't detect counter2 as a variable since it was inside the nested for loop. So how do I get out of this dilemma?
I'm trying to use the argument inputs (string respectively) and post the number of occurrences using an ascii table as reference and, as you see, there's just one obstacle from stopping me from accomplishing that.
Any ideas?
Your primary problem is that you have missed one important fact - your counts are not complete until after your loop has completed.
You therefore need to print out your counts in a separate loop after your first loop is complete.
public void test() {
String[] args = {"Hello"};
int[] occurenceCount = new int[256];
for (int word = 0; word < args.length; word++) {
System.out.println("Displaying per words: " + args[word]);
char[] splitWords = args[word].toCharArray();
for (int character = 0; character < splitWords.length; character++) {
System.out.println("Word spliced: " + splitWords[character]);
System.out.println("The number equivalent of " + splitWords[character] + " is "
+ (int) splitWords[character]);
occurenceCount[(int) splitWords[character]]++;
System.out.println("Word spliced: " + splitWords[character]);
}
}
// Scond loop to print the results.
for (int character = 0; character < occurenceCount.length; character++) {
int count = occurenceCount[character];
if (count > 0) {
System.out.println("The letter " + ((char) character)
+ " was shown " + count + " times.");
}
}
}
I have no idea on how to output a draw from a vote any help on with this would be appreciated.
At the moment it will allow a user to select the amount of candidates and then the user inputs details. Then the user will enter a vote, which is the candidate number, and type 999 to finish. The output will be the winner or winners(draw)the candidates with details and votes and the amount of spolit votes that is votes not in the range declared at the start.
int x;
char highestChar = '1';
char nextHighestChar = '1';
String alpha = "123456";
int largest=intVoteCount[1];
int nextLargest=intVoteCount[1];
for( x=1; x<=range; x++){
if(intVoteCount[x]>largest){
largest = intVoteCount[x];
highestChar = alpha.charAt(intLoopCount);
}
if(intVoteCount[x]>highestChar){
nextLargest = intVoteCount[x];
nextHighestChar = alpha.charAt(intLoopCount);
}
}
System.out.println("The winner is Candidate number "+ highestChar + " with " + largest + " votes.");
System.out.println("The winner is Candidate number "+ nextHighestChar + " with " + nextLargest + " votes.");
System.out.println("-----------------------------");
System.out.println("The Candidate votes are as follows.");
for (intLoopCount = 1; intLoopCount <= range; intLoopCount++) {
// Display all records.
// New Instance
System.out.println("");
System.out.println("Candidate " + intLoopCount + " "
+ strCandidateTitle[intLoopCount] + " "
+ strCandidateFirstname[intLoopCount] + " "
+ strCandidateSurname[intLoopCount] + " votes "
+ intVoteCount[intLoopCount]);
}
System.out.println("-----------------------------");
System.out.println("Vote Count Spolit: " + intVoteCountSpolit);
}
}
If largest == nextLargest you have a draw, so print out an appropriate message saying so; otherwise, you have an explicit winner.
Okay so I have built a denomination counter for the Indian currency rupees. Say, if you enter Rs. 3453, it gives this output:
Rs 1000 notes: 3
Rs 500 notes: 0
Rs 100 notes: 4
Rs 50 notes: 1
Rs 20 notes: 0
Rs 10 notes: 0
Rs 5 notes: 0
Rs 2 coins: 1
Rs 1 coin: 1
But I want this output and eliminate all the zeros,
Rs 1000 notes: 3
Rs 100 notes: 4
Rs 50 notes: 1
Rs 2 coins: 1
Rs 1 coin: 1
Here's my code:
import java.io.*;
import javax.swing.JOptionPane;
public class denom {
public static void main(String[] args) throws IOException{
String totalRsString;
int totalRs;
totalRsString = JOptionPane.showInputDialog(null, "Enter amount to be converted", "Denomination Conversion", JOptionPane.INFORMATION_MESSAGE);
totalRs = Integer.parseInt(totalRsString);
//Calculations begin here
int thousand, fh, h, f, twenty, t, fi, tw, o;
thousand = totalRs/1000;
int bal = totalRs - (1000*thousand);
fh = bal/500;
bal = bal - (500*fh);
h = bal/100;
bal = bal - (100 * h);
f = bal/50;
bal = bal - (50*f);
twenty = bal/20;
bal = bal - (20*twenty);
t = bal/10;
bal = bal-(10*t);
fi = bal/5;
bal = bal - (5*fi);
tw = bal/2;
bal = bal - (2*tw);
o = bal/1;
bal = bal - (1*o);
//End of calculation
//Print work.
JOptionPane.showMessageDialog(null, "Total Entered is Rs." + totalRsString + "\n" + "\nThousand rupee notes: " + thousand + "\nFive Hundred Notes: " + fh + "\nHundred notes: " + h + "\nFifty notes: " + f + "\nTwenty notes: " + twenty + "\nTen notes: " + t + "\nFive notes: " + fi +
"\nTwo coins: " + tw + "\nOne coins: " + o);
}
}
Rather than building your string as a single expression of the form ... + ... + ..., you can use a StringBuilder (see Javadoc for java.lang.StringBuilder) to assemble it across several statements. For example, something like this:
JOptionPane.showMessageDialog(null, "foo: " + 17 + "\n" + "bar" + 18 + "\n");
can be rewritten like this:
StringBuilder message = new StringBuilder();
message.append("foo: ").append(17).append("\n");
message.append("bar: ").append(18).append("\n");
JOptionPane.showMessageDialog(null, message.toString());
By using this approach, you can wrap any of the individual "append" statements in an if-block that makes sure the value is nonzero before adding it to the string.
As an alternative, consider using an enum to hold the value, kind and count for each form of Currency:
private enum Kind {
Coins, Notes
};
private enum Currency {
// …
Ten(10, Kind.Notes),
Five(5, Kind.Notes),
Two(2, Kind.Coins),
One(1, Kind.Coins);
private int value;
private Kind kind;
private int count;
private Currency(int value, Kind kind) {
this.value = value;
this.kind = kind;
}
};
Then your convert() method can iterate through the Currency instances and return a List<Currency> that includes only non-zero counts.
private static List<Currency> convert(int amount) {
List<Currency> list = new ArrayList<>();
int balance = amount;
for (Currency currency : Currency.values()) {
// update currency.count
// update balance;
if (currency.count != 0) {
list.add(currency);
}
}
return list;
}
Finally, you can loop though the List<Currency> to print the result:
List<Currency> list = convert(3453);
for (Currency currency : list) {
System.out.println("Rs "
+ currency.value + " "
+ currency.kind + ": "
+ currency.count);
}
You need to build the output string step-by-step. If the corresponding number of coins or notes for that specific input is equal to zero, you should skip that element in the final string.
Something like:
string output = "Total Entered is Rs." + totalRsString + "\n";
if(thousand == 0){
output += "\nThousand rupee notes: " + thousand;
}
/* Here you will do the same for the rest of notes and coins */
JOptionsPane.showMessageDialog(null, output);
Well, this is a lazy solution. But it's up to you to implement it in a more elegant way.
try reducing the number of variables you are creating. See the ones which can be reused.
StringBuilder sb = new StringBuilder();
int totalRs = 5500;
int bal = totalRs;
int numNotes =0;
if ((numNotes =bal/1000) > 0){
sb.append("Rs 1000 notes: " + numNotes + "\n");
bal = bal - (1000 * numNotes);
}
if ((numNotes =bal/500) > 0) {
sb.append("Rs 500 notes: " + numNotes + "\n");
bal = bal - (500 * numNotes);
}
I am attempting to search a user input array of text with another user input array of search terms using nested loops and then output the search terms with the number of times they appear in the text along with the percentage of total text. I think I am on the right track and my issue is that the counter is not resetting each time the if statement is true. I am very new to programming -- so I could be completely wrong. Below is the entire program. If anyone could take a look and give me a hand at figuring out what my issue is I would be eternally grateful.
public class termFrequency {
public static void main(String[] args) {
String searchTextPeriod, searchTextComma, searchTextApostrophe, searchTextColon, searchTextExclamation,
searchTextQuestion, searchText, searchTerm;
int counter=0, total, searchIndex=0, termIndex=0;
double percentage=0.0;
String [] searchArray, termArray;
searchText = JOptionPane.showInputDialog("Enter a sentence that is at least 20 words long");
//removes some common punctuation from the searchable text
searchTextPeriod = searchText.replace(".", "");
searchTextComma = searchTextPeriod.replace(",", "");
searchTextApostrophe = searchTextComma.replace("'", " ");
searchTextColon = searchTextApostrophe.replace(":", " ");
searchTextExclamation = searchTextColon.replace("!", "");
searchTextQuestion = searchTextExclamation.replace("?", "");
searchArray = searchTextQuestion.split(" "); //splits the sentence and and puts it into an array
total=searchArray.length;
System.out.println("There are " +total +" words in your sentence");
searchTerm = JOptionPane.showInputDialog("Enter your search terms here seperated by a space");
termArray = searchTerm.split(" ");
DecimalFormat two = new DecimalFormat("#0.00");
boolean found = false;
for (termIndex=0; termIndex<termArray.length; termIndex++)
{
for (searchIndex=0; searchIndex<searchArray.length; searchIndex++)
if (termArray[termIndex].equalsIgnoreCase(searchArray[searchIndex]))
{
counter++;
found = true;
percentage= ((double) counter/(double)total) * 100;
}
if (found)
System.out.println("Search word " + "\'" + termArray[termIndex] + "\' is found " +counter +" times. That is "+ two.format(percentage)+"% of the statement." );
else
System.out.println("Search word " + "\'" + termArray[termIndex] + "\' is not found in the statement.");
}
}
}
}
You have to move the if/else on "found" from the inner loop to the end of the first loop.
You also need to reset the boolean and the counter in the first loop, like that you start the analysis of each new word in termArray with initial values.
for (termIndex=0; termIndex<termArray.length; termIndex++)
{
counter=0; //Reset the counter for each word in termArray
found=false; //Reset the "found" flag for each word in termArray
for (searchIndex=0; searchIndex<searchArray.length; searchIndex++)
if (termArray[termIndex].equalsIgnoreCase(searchArray[searchIndex]))
{
counter++;
percentage= ((double) counter/(double)total) * 100;
found=true
System.out.println("Search word " + "\'" + termArray[termIndex] + "\' is found " +counter +" times. That is "+ two.format(percentage)+"% of the statement." );
}
}
if (found)
System.out.println("Search word " + "\'" + termArray[termIndex] + "\' is found " +counter +" times. That is "+ two.format(percentage)+"% of the statement." );
else
System.out.println("Search word " + "\'" + termArray[termIndex] + "\' is not found in the statement.");
}
By the way you don't really need the "found" var, now if counter == 0 you know that the word has not been found in searchArray.
Move found = false inside of the first loop. that way it will be reset to false with each iteration. Right now if it is ever changed to true it stays true for the rest of the process.