What's wrong with this randomized string and if-statement in java - java

I'm wetting my feet in java, and I've stumbled upon an issue. I suspect there might be already an answer for it, but I'm too much of a novice to know what it is I should be looking for - it also means my terminology might not be correct.
In the following code, I'm trying to create a random choice from an array of words, then use an if-statement to either display or not display the word. The problem is, although the condition of the if-statement is met (either the string "cat" or the string "dog" are obtained), the action displays any of the listed words, instead of either "cat" or "dog"
I suspect that when I use System.out.println(exampleWord()); in line 10, the routine obtains a new value from the array, effectively ignoring the if-statement.
What's the easiest way around this?
import java.util.Random;
public class Phrasing {
String word;
public static void main(String[] args) {
int i = 1;
while (i < 9) {
if ("cat".equals(exampleWord()) || "dog".equals(exampleWord())) {
System.out.println(exampleWord());
i++;
}
}
}
public static String exampleWord() {
String[] listedWords = {"cat", "dog", "horse", "fish", "turtle", "mouse"};
Random random = new Random();
int index = random.nextInt(listedWords.length);
Phrasing wordOutput;
wordOutput = new Phrasing();
wordOutput.word = listedWords[index];
return (wordOutput.word);
}
}

Yes, you are right. Each time you call exampleWord(), a random word is generated. Try storing it in a String once.
public static void main(String[] args) {
int i = 1;
while (i < 9) {
String s = exampleWord();
if ("cat".equals(s) || "dog".equals(s)) {
System.out.println(s);
i++;
}
}
}
Also, it seems like you are doing some work unnecessarily, in the exampleWord method. You could do
public static String exampleWord() {
String[] listedWords = {"cat", "dog", "horse", "fish", "turtle", "mouse"};
Random random = new Random();
return listedWords[random.nextInt(listedWords.length)];
}

You should generate the word only once and then perform checks and output it:
while (i < 9) {
String exampleWord = exampleWord();
if ("cat".equals(exampleWord) || "dog".equals(exampleWord)){
System.out.println(exampleWord);
i++;
}
}

The problem is that you are executing exampleWord() every time you compare "cat" or "dog" to the result, and then again you execute it to print the result.
Just execute exampleWord() one time inside the loop, store it in a variable and finally compare and print the result.
Something like:
String result = exampleWord()
if("cat".equals(result) || "dog".equals(result)) {
System.out.println(result);
i++;
}

Related

How would I write a statement that will loop continuously as long as an array contains a certain value in JAVA

How would I write a statement that will loop continuously as long as an array contains a certain value? I need it to continue to loop as long as an array contains a specific character, but stop looping if the array does not contain those said character values.
I kinda have this below, but I'm almost 100% sure it won't work
for(int PieceChecker = 0, PieceChecker < 1){
//Code that needs to be carried out
if (Arrays.asList(board).contains(♖)){
PieceChecker++;
}
}
It is easier to handle cases like these which involve just characters, by using a string than a list. Use an infinite for loop and break out of it once you find the absence of that character in it. You can use the indexOf for this purpose.
Here is the code snippet that might help you:
String board_string = new String(board);
for(;;) {
if(board_string.indexOf('♖') == -1) {
System.out.println("Breaking out of loop...");
break;
}
else {
//do something here
}
}
From question it is not clear that you want to loop around simple char array OR the list of character array.
Here I came up with something which might help.
private static char[] myCharArray = new char[] { '\u00A9', '\u00AE', '\u00DD', 'A', 'B' };
private static Logger _log = Logger.getLogger(Test.class.getCanonicalName());
public static void main(String[] args) {
// 1. Using character array directly
for (int i = 0; i < myCharArray.length; i++) {
while (myCharArray[i] == '\u00A9') {
_log.info("Inside char array as this condition holds true");
}
}
// 2. List of char arrays.
List<char[]> list = Arrays.asList(myCharArray);
for (char[] cs : list) {
for (char c : cs) {
while(c =='A'){
_log.info("Inside charToList array as this condition holds true");
}
}
}
}
just use a while loop. The basic construct could be
while (true) {
// test situation
if (!goodSituation()) {
break;
}
// do something here
}
while (Arrays.asList(board).contains("♖")) {
//do something
}
Edit based on #shmosel's comment:-
For primitive arrays like int[], you can use something like this in the while condition:-
IntStream.of(a).anyMatch(x -> x == 2)
For a primitive char array, you can use this condition:-
new String(cArr).indexOf('♖') > -1

Java programming - Class and method

I am new to Java programming and I had a task in class.
So the main thing was I had to make a public class named BankAccount with these 3: int number, String owner, int amount.
Then I had to make an array of 10 with this class and fill it up (the owner names were Name1, Name2, etc.).
Then I had to make a String array of 5 with 5 names in it (for example: "James", "Jack", etc.)
and then I had to kind of "modify" the owner names so that my program will attach one of the 5 names randomly to the end of the current owner names.
So it will be like this for example: Name2Jack, Name3James, etc.
I successfully did all of this.
But then.
My teacher told me to make another method which will decide, how many names do I have out of the 10 ownernames in which name X is present.
So I did this:
public static int Count(BankAccount[] accounts, String name){
int number=0;
for (i=0; i<accounts.length, i++){
if(accounts[i].owner.contains(name)==true)
number++;
}
return number;
}
At least if I remember correctly, it was this. Or something similar like that.
And this worked as well.
But then, my teacher said, how would I do it with not .contains but with .equals ?
And if I would do it with that, would I need 1 or 2 "=" marks?
I had no idea what she means, like I dont know how to do it with .equals... because the owner names are like Name1Jack for example..
She told me I would need 1 "=" mark instead of 2, and that I should look after this for the next class.
Can you guys actually tell me what she meant with this ".equals" method instead of the .contains one?
How could I do this with .equals , and I dont get it why would I need 1 "=" mark instead of 2 whatsoever.
Any help would be really appreciated!
It appears that you need to just change this one line:
From:
if (accounts[i].owner.contains(name) == true)
To:
if (accounts[i].owner.equals(name))
Here is a sample code with both variations:
public class BankAccountDemo {
public static void main(String[] args) {
BankAccount[] bankAccounts = new BankAccount[5];
bankAccounts[0] = (new BankAccount(1, "Name1James", 1000));
bankAccounts[1] = (new BankAccount(2, "Name2Jack", 2000));
bankAccounts[2] = (new BankAccount(3, "Name3Henry", 3000));
bankAccounts[3] = (new BankAccount(4, "Name4Jack", 4000));
bankAccounts[4] = (new BankAccount(5, "Name5James", 5000));
System.out.println("Check A:");
System.out.println(BankAccountDemo.Count(bankAccounts, "James"));
System.out.println(BankAccountDemo.Count2(bankAccounts, "James"));
System.out.println("Check B:");
System.out.println(BankAccountDemo.Count(bankAccounts, "Name5James"));
System.out.println(BankAccountDemo.Count2(bankAccounts, "Name5James"));
}
public static int Count(BankAccount[] accounts, String name) {
int number = 0;
for (int i = 0; i < accounts.length; i++) {
if (accounts[i].owner.contains(name) == true) {
number++;
}
}
return number;
}
public static int Count2(BankAccount[] accounts, String name) {
int number = 0;
for (int i = 0; i < accounts.length; i++) {
if (accounts[i].owner.equals(name)) {
number++;
}
}
return number;
}
}
Run output is:
Check A:
2
0
Check B:
1
1

Array in Method Header: error ']' expected (Java)

I'm quite new to arrays and methods, and I've been seeing this error recurring through several programs: error '[' expected.
In each occasion, it seems to correct itself as I adjust something else, but in this particular case, I am completely stumped.
By the way, I am using several methods and arrays to create a quiz (before you ask, yes, this is an assignment and I agree, a list is a better way to handle this data - but that is not an option).
It is possible that I am not passing the arrays correctly between methods, as I'm a little muddy on that process. From my understanding, in order to send/receive (i.e. import/export) an array or other variable between methods, I must declare that variable/array in the method header parameters.
import java.util.Scanner;
public class H7pseudo
{
public static void main(String[] args)
{
//call getAnswerkey method
getAnswerkey(answerkey[i]);
//call getAnswers method
getAnswers(answers[i]);
//call passed method? necessary or no?
boolean passed = passed(answerkey[i], answers[i], qMissed[i], points);
//Print results of grading
if (passed)
{
System.out.println("Congratulations! You passed.");
}
else
{
System.out.println("Try again, sucka. You FAILED.");
}
//call totalPoints
totalIncorrect(points);
//call questionsMissed
questionsMissed(qMissed[i]);
}
//get answer key (create answerkey array & export)
public static void getAnswerkey(answerkey[i])
{
//create answerkey array here
char[] answerkey;
//determine number of questions (indices)
answerkey = new char[20];
//input values (correct answers) for each index
//for our purposes today, the answer is always 'c'.
for (int i = 0; i <=20; i++)
{
answerkey[i] = 'c';
}
}
//get student answers (create answers array & export)
public static void getAnswers(answers[i])
{
//initialize scanner for user input
Scanner scan = new Scanner(System.in);
//create answer array here
char[] answers;
//determine number of questions (indices)
answers = new char[20];
//prompt for user input as values of each index
for (int i = 0; i <= 20; i++) {
answers[i] = scan.nextChar();
}
}
//grade student answers (import & compare index values of arrays:answers&answerkey
//create & export qMissed array
public static boolean passed(answerkey[i], answers[i], qMissed[i], points)
{
int points = 0;
//create new array: qMissed
boolean[] qMissed;
//determine number of questions to be graded
qMissed = new boolean[20];
//initialize values for array
for (int i = 0; i <= 20; i++) {
qMissed[i] = false;
}
//cycle through indices of answerkey[i] & answers[i];
for (int i = 0; i =< 20; i++)
{
if (answers[i] == answerkey[i])
{
correct = true;
points = points+1;
qMissed[i] = true;
}
else {
qMissed[i] = false;
}
}
//evaluate whether or not the student passed (15+ correct answers)
if (points >= 15)
{
passed = true;
}
else
{
passed = false;
}
return passed;
}
public static void totalIncorrect(points)
{
int missed = 20 - points;
System.out.println("You missed " + missed + " questions.");
}
public static void questionsMissed(qMissed[i])
{
// for each index of the array qMissed...
for (int i = 0; i < qMissed.length; i++)
{
//...print correct and false answers.
system.out.println(i + ": " + qMissed[i] + "\n");
}
}
}
You can't define array size in the method signature, in Java.
public static void getAnswerkey(answerkey[i])
You can't put anything inside the [] in a method declaration. Also, you have to mention the type:
public static void getAnswerKey(char[] answerkey)
This is not the only reason your code won't work as intended, but I'll leave the rest as part of the exercise.
Look at your method definitions:
public static void questionsMissed(qMissed[i])
This is wrong. You should define the type of the variable and it should not contain [i] like an element of an array. It should be something like this:
public static void questionsMissed(int qMissed)
Or if you want to pass the array, write it like this:
public static void questionsMissed(int[] qMissed)
Apart of this, there are other several errors in your code:
getAnswerkey(answerkey[i]); //answerkey is not defined
getAnswers(answers[i]); //answers is not defined
It would be better if you start reading a Java tutorial first.
I want to vote up Luiggi's answer, but I don't have enough reputation to do that :)
Congrats, cordivia, on getting started with Java!
Here is how an array is declared:
type[] arrayName = new type[numberOfElements]
For example, you did this right in your method definition for getAnswerkey():
char[] answerkey;
answerkey = new char[20];
The part in the method definition inside the parentheses defines the kind of data the method is willing to accept from the outside. So if you don't need to put something into the method to get something out of it, you don't need to put anything in the parentheses. Define the method like this:
getAnswerkey() {
...But that's not the whole story. If you want to get something out of the method, it needs to have a return type as well. A return type is what you're gonna get out of the method when the method's done doing it's magic. For example, if you want to get an int array out of a method you would do something like this:
public static int getTheInteger() {
Since you want an array of chars from the method, you'll want to do something like this:
public static char[] getAnswerkey() {
So that's how you get a method to give you something back. If don't want anything back, you put void:
public static void noMarshmallows() {
Now, when you use the method, you're gonna need to do something with what it gives you, or it did all that work for nothing. So you need to store the return value in a variable when you call the array (calling methods is what you've been doing in main). You know how to store something in a variable. You use the '=' operator:
int myVeryFavoriteNumber;
myVeryFavoriteNumber = 5;
So, you do the same thing when you're getting something out of an array. You assign the return value to a variable. If you want to do this with an array, do this:
int[] myFavs;
myFavs = getMyFavoriteNumbers();
Same with chars:
char[] answerKey;
answerKey = getAnswerKey();
Voila! Your answer key is now right out in the open for the rest of main to see :)
Now, if you want to put something into a method and have it do something with what you put in, you define a parameter. You know how this works. It's just like declaring a variable, and that's exactly what it is. Parameters go in the parentheses and only the method using the parameter sees that variable name (it's local). Something like this:
public static void plusOneToAll (int[] numbers) {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = numbers[i] + 1;
}
}
Notice int[] numbers in the parentheses. The type being passed in is int[] or integer array. numbers is just the parameter name. It functions just like a variable, but it is declared locally (inside the parentheses) and use locally (inside the method). So, if you wanted to compare the answers from two arrays and return the number of matches (like a total score for instance), you would do something like this:
public static int getTotalScore (char[] correctAnswers, char[] userAnswers) {
int totalScore = 0;
for (int i = 0; i < correctAnswers.length; i++) {
if (userAnswers[i] == correctAnswers[i]) {
totalScore = totalScore + 1;
}
}
return totalScore;
}
Notice the return type: int (written before the method name). Inside the array I'm using the variable totalScore to keep track of the number of times the answers match. The method takes two char arrays from the outside and uses them on the inside. Finally, I return an int: totalScore. That kicks the value of totalScore back out to whatever called it (main).
If I might add one last thing: Do yourself a favor and go pick up a copy of Head First Java. It's hard to find a good tutorial online and Java textbooks are just plain boring. The Head First series are kind of like coloring books for adults.
Best of luck!

Simple Array: Check to see if value matches

I am simply trying to see if the inputted value matches a value that is already in the array and if it does return "Valid". I realize this is very simple but I cannot get this to work:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String[] accountNums = { "5658845", "8080152", "1005231", "4520125", "4562555",
"6545231", "7895122", "5552012", "3852085", "8777541",
"5050552", "7576651", "8451277", "7881200", "1302850",
"1250255", "4581002" };
String newAccount;
String test = "Invalid";
newAccount = keyboard.next();
for (int i = 0; i < accountNums.length; i++)
{
if(newAccount == accountNums[i])
{
test = "Valid";
}
}
System.out.println(test);
}
}
thank you for any assistance (and patience)
Use equals method. Check here why to.
if (newAccount.equals(accountNums[i]))
Jayamohan's answer is correct and working but I suggest working with integers rather than Strings. It is a more effective approach as CPUs handle numbers (integers) with a lot more ease than they handle Strings.
What has to be done in this case is change newAccount and accountNums to ints instead of Strings and also remove all the quotation marks from the accountNums initialization. Instead of calling keyboard.next() you can call keyboard.nextInt(), which returns an integer. The if-statement is fine as it is.
Why are you using an array?
List<String> accountNums = Arrays.asList( "5658845", "8080152", "1005231", "4520125", "4562555",
"6545231", "7895122", "5552012", "3852085", "8777541",
"5050552", "7576651", "8451277", "7881200", "1302850",
"1250255", "4581002" );
String test = "Invalid";
Then you just need this (no loop):
if (accountNums.contains(newAccount)) {
test = "Valid";
}
Plus, it's easier to read and understand.
You cannot compare strings with ==
You must use .equals()

Java class Anagrams

Im new to the java programming language and need help writing a class Anagrams that prints the permutations of words in a sentence. Example: red car -> red car, car red. This is what i have written so far and i think im on the right track and even though my code is not finished, i would at least like to get it to run.
import javax.swing.JOptionPane;
public class Anagrams
{
private String x;
private char[] xarray;
private String[] words;
public void Anagrams(String phrase1)
{
x = phrase1;
}
public void printPerms()
{
int perms = 0;
xarray = x.toCharArray();
for (int i = 0; i < x.length(); i++)
{
if(xarray[i] == ' ') perms = perms + 1;
}
words = x.split(" ");
for (int i = 0; i < perms; i++)
{
System.out.println(words[i]);
}
}
public void main(String args[])
{
String phrase1 = JOptionPane.showInputDialog("Enter phrase 1.");
Anagrams(phrase1);
printPerms();
}
}
This is the error i get when i try to run.
Exception in thread "main" java.lang.NoSuchMethodError: main
Right now im just trying to get my program to run not print out the permutations. I think i can figure that out once it at least print something out. Can someone tell me why it doesnt run and how do you get input from the user like c++ cin>>, if there is another way other than JOptionPane.
Thanks
A main method needs to be static.
How about this:
public static void main(String args[])
{
String phrase1 = JOptionPane.showInputDialog("Enter phrase 1.");
new Anagrams(phrase1).printPerms();
}
Even After Declaring your main method as static you may or may not be required to make all other methods as static(If calling methods dirctly without use of objects make methods as static).Because a static method can call or use only static data memebers or methods.
And in your code because you have defined all the methods in the same class which contains main method you need to make other methods also as static.
The method should return true if the two arguments are anagrams of each other, false if they are not.
For example, anagram(“glob”, “blog”) would return true;and anagram(“glob”, “blag”) false.
Assumes that the input strings will contain only letters and spaces. Treat upper- and lower-case letters as identical, and ignore spaces.
<br/> Uses the following algorithm:
<ul> <li> clean input strings from spaces and convert to lower case
</li> <li>convert to char array and sort them
</li> <li>if sorted arrays are identical, words are anagrams
</li></ul>
*/
public static boolean anagram(String str1, String str2)
{
//handle nulls
if(str1==null && str2==null)
return true;
else if( (str1==null && str2!=null) || (str2==null && str1!=null) )
return false;
//clean input strings from spaces and convert to lower case
String s1 = str1.replace(" ", "").toLowerCase();
String s2 = str2.replace(" ", "").toLowerCase();
//convert to char array and sort them
char[] cArr1 = s1.toCharArray();
char[] cArr2 = s2.toCharArray();
java.util.Arrays.sort(cArr1);
java.util.Arrays.sort(cArr2);
//if sorted arrays are identical, words are anagrams
s1 = new String(cArr1);
s2 = new String(cArr2);
return s1.equals(s2);
}
public static void main(String[] args)
{
//test: anagram(“glob”, “blog”) would return true; anagram(“glob”, “blag”) false.
System.out.println("anagram(“glob”, “blog”):"+(anagram("glob", "blog")));
System.out.println("anagram(“glob”, “blag”):"+(anagram("glob", "blag")));
}
You are missing static in:
public void main(String args[])
The main method needs to be static.
Also you are calling printPerms from main directly (without an object) so it must be made static as well or call them on a Anagram class object.
You are missing the new keyword while creating the object:
Anagrams(phrase1);
printPerms();
try
new Anagrams(phrase1).printPerms();
Also there is no Anagram class constructor that takes a String. What you have is a method named Anagram as you've specified the return type.
public void Anagrams(String phrase1) {
drop the void.

Categories