Can someone please explain this code for me, especially this part.
int lastpos = message.length() - 1;
Why did he add - 1 ?
==
System.out.print("What is your message? ");
String message = kb.nextLine();
System.out.println("\nYour message is " + message.length() + " characters long.");
System.out.println("The first character is at position 0 and is '" + message.charAt(0) + "'.");
int lastpos = message.length() - 1;
System.out.println("The last character is at position " + lastpos + " and is '" + message.charAt(lastpos) + "'.");
System.out.println("\nHere are all the characters, one at a time:\n");
for ( int i=0; i < message.length(); i++ )
{
System.out.println("\t" + i + " - '" + message.charAt(i) + "'");
}
int a_count = 0;
for ( int i=0; i<message.length(); i++ )
{
char letter = message.charAt(i);
if ( letter == 'a' || letter == 'A' )
{
a_count++;
}
}
System.out.println("\nYour message contains the letter 'a' " + a_count + " times. Isn't that interesting?");
}
}
Because indices start at 0 . If you have a list of {0, 1, 2}, note that it has a length of 3, but the last index is only 2. - 1 is used to correct for that.
If you iterated to the element at index 3 (the length of the list), you would go off the end of the list, causing an IndexOutOfBoundsException.
Note, I used lists as an example for ease of understanding, but it's exactly the same when it comes to Strings. All iterables start at an index of 0.
Suppose you have a String "Abdullah" and you want to print last character of that string then
int lastpos = message.length() - 1
Iine gives you last character of that String.
So in given code that line print the last character of the input String.
Related
I'm trying to complete this code for my class and I just can't get this part to work.
I need the three input numbers to be compared with the three random numbers, when I run the code, after I put the inputs in, the only thing that prints out is the else statement even if some of the numbers matched.
for(int x=0; x<=array.length - 1; x++) {
if(array[0] == Rand[0] && array[1] == Rand[1] && array[2] == Rand[2]) {
System.out.println("Your guesses are: " + array[0] + " " + array[1] + " " + array[2]);
System.out.println("Lucky numbers are: " + Rand1 + " " + Rand2 + " " + Rand3);
System.out.println("You won $1000!");
break;
} else if(array[x] == Rand[0] && array[x] == Rand[1] && array[x] == Rand[2]) {
System.out.println("Your guesses are: " + array[0] + " " + array[1] + " " + array[2]);
System.out.println("Lucky numbers are: " + Rand1 + " " + Rand2 + " " + Rand3);
System.out.println("You won $100");
break;
} else if(array[x] == Rand[0] && array[x] == Rand[1] ||
array[x] == Rand[1] && array[x] == Rand[2] ||
array[x] == Rand[0] && array[x] == Rand[2]) {
System.out.println("Your guesses are: " + array[0] + " " + array[1] + " " + array[2]);
System.out.println("Lucky numbers are: " + Rand1 + " " + Rand2 + " " + Rand3);
System.out.println("You won $30!");
break;
} else if(array[x] == Rand[0] || array[x] == Rand[1] || array[x] == Rand[2]) {
System.out.println("Your guesses are: " + array[0] + " " + array[1] + " " + array[2]);
System.out.println("Lucky numbers are: " + Rand1 + " " + Rand2 + " " + Rand3);
System.out.println("You won $5");
} else {
System.out.println("Your guesses are: " + array[0] + " " + array[1] + " " + array[2]);
System.out.println("Lucky numbers are: " + Rand1 + " " + Rand2 + " " + Rand3);
System.out.println("You won nothing");
break;
}
}
if you get 1 match($5) 2 matches(30) 3 out of order ($100) and 3 in exact order ($1000)
So let's say array and rand have the same length and all numbers in rand are different (so no 1, 1, 5 or so).
Then you'd check the following:
For each index check the element in array and rand at that index. If all match you are done, the user guessed 3 in order.
If not all match then you check each element in array against each element in rand and count the number of matches. That number then tells you whether the user won 0, 5, 30 or 100 bucks.
Note that I deliberately didn't post any code because that code is "for your class" and thus it is your task to actually write the code and learn something from doing so.
Edit
In your comment you state that the 3 random numbers could be all the same. That would require you to go about it a little differently. One approach might be to have a temporary copy of rand and when you found a match you "remove" the element from that copy (e.g. if rand is an int[] array you could set the matching element to -1 and when comparing the elements of array with those of rand you ignore any that have the value -1).
Using lists might be easier (i.e. you actually remove any matches) but I assume you didn't learn about those yet.
Try this approach of counting how many numbers are matching in both the ArrayLists
(The work is incomplete you can finish it off):
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
Random rn = new Random();
int max=1000;
int min=10;
ArrayList<Integer>random=new ArrayList<>();
for (int i=0;i<3;i++){
random.add(rn.nextInt(max - min + 1) + min);
System.out.println(random.get(i));
}
ArrayList<Integer>array=new ArrayList<>();
for (int i=0;i<3;i++){
array.add(input.nextInt());
}
int count=0;
for (int i=0; i<3; i++){
for (int j=0; j<3; j++){
if (random.get(i).equals(array.get(j)))
count++;
}
}
System.out.println(count);
}
In this approach, I am taking in 3 inputs in array and generating 3 random numbers in random between 10 and 1000(you can change this of course by changing min and max)
After checking how many entries match, and counting them in count, you can use that count in your if-else structure to give the prizes. for example if(count==2) give $100 or whatever. You can add checks in so that the Random numbers are unique and so that the count value is accurate.
I'm trying to change my code so that it prints how the frequency of the letters and not how many there is e.g. "I am a man I am a man" should give the same answer as "I am a man" since the relative proportions of each letter to the whole sequence is the same.
So the desired output would be:
Letter A: Count: 0.43
Letter I: Count: 0.14
Letter M: Count: 0.29
Letter N: Count: 0.14
So the count will always add up to 1.0.
At the moment, my code just counts and displays how many times the letter appears, is this simple to change?
//
You could try something like this to get the percent of total characters:
int total = 0;
for(int i = 0; i < lettersArray.length; i ++)
{
total += letterArray[i];
}
for (char characters = 'a'; characters <= 'z'; characters++) {
int index = characters - 'a';
//print out the analysis
System.out.println("'" + characters + "' entered " + (((double)letterArray[index] / (double)total))
+ " times");
}}}
System.out.println("'" + characters + "' entered " + letterArray[index] /
(double)line.length() + " times");
I have a task to print n frequently used words based on their count values across multiple files.
Now the issue is after printing n words, I have to print all the ties at the last position
for instance if I printed 10 frequently used words based on the highest count
and the output comes like this when I use a for loop.
CODE
int listSize = newList.size() >= 10 ? 10 : newList.size();
for (int k = 0; k < listSize; k++) {
Words w = newList.get(k);
System.out.println("Word : " + ++j + " " + w.getWord() + " "
+ w.getCount());
// System.out.println(w.getWord());
}
OUTPUT :
word 1 : liked 104
word 2 : hello 98
....
....
....
word 10 : picnic 15
now If I encounter words further with the same count that is 15 I have to print them also
if I have five words with the same word count 15
I have to print all of them that is all ties for the last position must be reported like this
**OUTPUT :**
word 11 : camera 15
word 12 : monkey 15
word 13 : carrot 15
word 14 : penguin 15
word 15 : bottle 15
how to implement this case guide me thanks in advance
If newList is sorted by getCount then the simpliest way to print words with same count as last printed word is:
int k; // init k before the cycle
for (k = 0; k < listSize; k++) {
Words w = newList.get(k);
System.out.println("Word : " + ++j + " " + w.getWord() + " "
+ w.getCount());
// System.out.println(w.getWord());
}
if (k > 0) {
int lastCount = newList.get(k - 1).getCount(); // last printed count
// print words from the k-th
while (k < newList.size()
&& newList.get(k).getCount() == lastCount) {
Words w = newList.get(k);
System.out.println("Word : " + ++j + " " + w.getWord() + " "
+ w.getCount());
++k;
}
}
I am trying to count the frequency of ASCII characters from a String input that was converted to a character array.
I tried to implement the accepted answer from this thread, along with my code to print the results in a 3-column table.
package com.mypackage.mp;
import java.util.*;
public class AsciiCounter {
public static void displayAsciiOccurrence(String inputWords) {
int[] iaCount = new int[256]; //this
char[] caInputWords = inputWords.toCharArray();
int i = 0;
for(i = 0; i < caInputWords.length; i++) {
iaCount[caInputWords[i]]++;
}
// Print table
System.out.println("\nDEC\tASCII\tFREQ");
for(int ctr = 0; ctr < 256; ctr++) {
System.out.println(ctr +"\t" + (char) (ctr) + "\t" + iaCount[caInputWords[i]]); //this
}
}
public static void main(String[] args) {
String inputWords = null;
Scanner scn = new Scanner(System.in);
System.out.print("Enter words: ");
inputWords = scn.nextLine();
displayAsciiOccurrence(inputWords); //this
scn.close();
}
}
However, it is returning an ArrayIndexOutOfBoundsException. My desired output is supposed to be:
Enter words: AA bC! d
DEC ASCII FREQ
0
.. .. ..
32 2
33 ! 1
.. .. ..
65 A 2
66 B 0
67 C 1
..
98 b 1
99 c 0
100 d 1
..
255
(The .. pertains to whatever is in between and must print 0 as frequency.)
Stack Trace:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
at
com.mypackage.mp.AsciiCounter.displayAsciiOccurrence(AsciiCounter.java:20)
at
com.mypackage.mp.AsciiCounter.main(AsciiCounter.java:31)
The error is in your printing loop:
System.out.println(ctr +"\t" + (char) (ctr) + "\t" + iaCount[caInputWords[i]]);
Since i hasn't changed since the first loop, it is equal to caInputWords.length at this point.
I guess you just meant:
System.out.println(ctr +"\t" + (char) (ctr) + "\t" + iaCount[ctr]);
As a side note, you might not want to print all the ASCII characters themselves. Some of them don't represent printable characters or are whitespace. One simple way around this is to check that iaCount[ctr] > 0 before printing so you only print characters that were in the String to begin with.
You have a problem in your second loop:
for(int ctr = 0; ctr < 256; ctr++) {
System.out.println(ctr +"\t" + (char) (ctr) + "\t"
+ iaCount[caInputWords[i]] // HERE
);
}
You meant iaCount[ctr]! You use i which is 256 when you enter this loop, since it has been set to this value by your previous loop. And since the iaCount array is only 256 chars long, this index is out of bounds.
Also, you fail to check what happens if you enter a non ASCII character.
To avoid this kind of error, change your first for loop to:
for(int i = 0; i < 256; i++)
Doing so in your first loop would have shown that i didn't exist in the second.
the i variable has not been reset. but you don't need to use variable i at all after the frequency calculation. You need to use ctr for frequency of all the characters.
for(int ctr = 0; ctr < 256; ctr++) {
System.out.println(ctr +"\t" + (char) (ctr) + "\t" + iaCount[ctr]);
}
That line can throw exception.
System.out.println(ctr +"\t" + (char) (ctr) + "\t" + iaCount[caInputWords[i]]);
Change it to that
for(int ctr = 0; ctr < 256; ctr++) {
System.out.println(ctr +"\t" + (char) (ctr) + "\t" + iaCount[ctr]);
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I am trying to make a guessing game program with Java and need help Here is what I have so far.
public class CodeGuessingGame {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] guess = {0, 1, 2, 3, 4};
int[] secretNumber = {0, 1, 2, 3, 4};
System.out.println("Let the game begin...");
System.out.println("Guess my secret code, consisting of 1 and 2");
System.out.println(" ");
for (int i=0; i<5; i++) {
System.out.print("Guess number " + (i+1) + " (1 or 2): ");
guess[i] = scan.nextInt();
}
System.out.println(" ");
System.out.println("Your guess: " + "[" + guess[0] + "]" +
"[" + guess[1] + "]" + "[" + guess[2] + "]" +
"[" + guess[3] + "]" + "[" + guess[4] + "]");
for (int i=0; i<5; i++) {
secretNumber[i] = (int) (Math.random() * 2 + 1);
}
System.out.print("Secret code: " + "[" + secretNumber[0] + "]" +
"[" + secretNumber[1] + "]" + "[" + secretNumber[2] + "]" +
"[" + secretNumber[3] + "]" + "[" + secretNumber[4] + "]");
}
The output of this code should be the following:
Let the game begin...
Guess my secret code, consisting of 1 and 2
Guess number 1 (1 or 2): 1
Guess number 2 (1 or 2): 2
Guess number 3 (1 or 2): 2
Guess number 4 (1 or 2): 1
Guess number 5 (1 or 2): 1
Your guess: [1][2][2][1][1]
Secret code: [2][1][2][1][2]
This code goes on forever. You must be able to win or lose the game. If you get 3 or more numbers of the secret code right, you win. If you don't get 3 or more numbers right, you lose. How should I do this?
Add this at the end of the main.
int count = 0;
for (int i=0; i<5; i++) {
if (secretNumber[i] == guess[i])
count++;
}
if (count >= 3)
System.out.print("You guessed " + count + " numbers correct, therefore you win");
else
System.out.print("You only guessed " + count + " number(s) correct, therefore you lose");
You should split up the behavior of your code into different methods. For example,
public int void recieveGuess(int guessNum, Scanner scan){
System.out.print("Guess number ") + guessNum + "(1 or 2): ");
return scan.nextInt(); //Assuming the user entered an int. May want to check for that.
}
public int compareGuess(int[] secret, int[] guesses){
int count = 0;
for(int i = 0; i < secret.length; i++){
if(secret[i] == guess[i]){
count++;
}
}
return count;
}
Then in your main you can just print the starting information, then loop through recieveGuess however many times you want, and then compare at the end.
if(compareGuess(secretNumber, guess) >= 3){
//they won
} else {
//they lost
}
Also you should just initialize secretNumber to new int[5]. This will create an array of length five with all zeros or whatever length you want. Then fill the secret number with random numbers. Like this:
int[] secretNumber = new int[5];
int[] guess = new int[5];
To do this, you can just define a variable a and increment it up one for each right answer. For example:
int a;
if (answer1 == true1){
a = a + 1;
}
if (answer2 == true2){
a = a + 1;
}
//check the rest
if (a > 2){
System.out.println("You win");
}
else{
System.out.println("You lose");
}