This question already has answers here:
How do I determine whether an array contains a particular value in Java?
(30 answers)
Closed 7 years ago.
I want to compare from a void main method where there is a array and a string. so what I want to do is to compare with if name is in the array. return true else return false. But I cant get it to work. It gives me false on both. And I don't know why?
public boolean isActor(String name) {
if(name.equals(actors)) {
return true;
}else {
return false;
}
}
public static void main(String[] args) {
String[] actors = {"Ulla Skoog", "Suzanne Reuter", "Peter Dalle"} ;
Dvd d1 = new Dvd(10327, "Yrrol", "Peter Dalle", actors, 88);
System.out.println("Medverkar Kalle Kula i Lorry: " + d1.isActor("Kalle kula"));
System.out.println("Medverkar Ulla Skoog i Lorry: " + d1.isActor("Ulla Skoog"));
}
Any help would be appreciated !
EDIT: So I tried to do if(Arrays.asList(actors).contains(name)) and yes it worked. Problem is I might now be allowed to do it under a test which can make me losing points and I tried to make a for loop and by that make a equals statement but still getting the same result which is both false.
EDIT2: Also tried to do this
public boolean isActor(String name) {
for(String s: actors){
if(s.equals(actors))
return true;
}
return false;
}
but still got the same result of both false
EDIT3:
What I want to do is to make e method which is ( public boolean isActor(String name) { ) and with that I want to make a if-statement which should make a algorithm by saying "If this name is on this array. make it say true. If its not in the array. Say its false." Thats what im trying to do.
You have to test each item in array:
public boolean isActor(String name) {
for (String actor : actors) {
if (name.equals(actor) {
return true;
}
}
return false;
}
public boolean isActor(String name, List<String> actorList) {
if(actorList.contains(name)) {
return true;
}else {
return false;
}
}
public static void main(String[] args) {
String[] actors = {"Ulla Skoog", "Suzanne Reuter", "Peter Dalle"} ;
List<String> actorList = Arrays.asList ( actors);
Dvd d1 = new Dvd(10327, "Yrrol", "Peter Dalle", actors, 88);
System.out.println("Medverkar Kalle Kula i Lorry: " + d1.isActor("Kalle kula",actors));
System.out.println("Medverkar Ulla Skoog i Lorry: " + d1.isActor("Ulla Skoog",actors));
}
Related
the same code when solving problems on codingbat works , but not in my IDE
public class Bark {
public static void main(String[] args) {
String lo = "hi there";
String shank = lo.substring(0 , 2);
if (shank.equals("hi")) return true;
else return false;
}}
My guess here is that your expectations have to with an artifact of some sort. Certainly, the check on shank should reveal that it is equal to hi. You are returning a boolean value from a method which is void, and has no return type. Consider the following version, which works as expected:
public static void main(String[] args) {
String lo = "hi there";
String shank = lo.substring(0 , 2);
if ("hi".equals(shank)) {
System.out.println("EQUAL");
}
else {
System.out.println("NOT EQUAL");
}
}
Perhaps CodingBat has some hooks into your code which aren't so obvious, resulting in the code "working" there, but not in your IDE.
I have an enum class with values:
enum carBrand{BMW,HONDA,MERC,AUDI};
And there's an array called Sales with Array values:
sales[] = {CHEVVY, BMW , MERC, AUDI};
So how could I check that the sales[] has all the values of enum carBrand?
I'm trying to put it in a for loop as:
for(int i = 0; i<sales.length;i++){
if(carBrand.sales == sales[i]){
return true;
}
return false;
}
Add carBrand values to list
loop sales, remove the carBrand from the list
check if list is empty, if so they have all the values
Note: Class names should be names in PascalCase (CarBrand, Sales)
I would, personally, suggest using a list object rather than an Array where you are using such, however, this should work.
public static boolean checkArray(carBrand[] array) {
for (carBrand c : carBrand.values()) {
boolean found = false;
for (carBrand a : array) {
if (a == c) {
found = true;
break;
}
}
if (!found) {
return false;
}
}
return true;
}
where the "array" parameter would be invoked as the sales object in your code.
This code will return false if not every enum value exists within your array.
Off-topic:
Things like this are actually all over the internet - here, google, even Bing (as garbo as Bing is), so searching before requesting help, probably a viable choice
public class Enumeration {
enum carBrand{BMW,HONDA,MERC,AUDI};
public static void main(String[] args) {
String sales[] = {"CHEVVY", "BMW" , "MERC", "AUDI"};
for(carBrand brand:carBrand.values()) {
boolean bran=false;
for(int i=0;i<sales.length;i++) {
if(brand.toString()==sales[i]) {
bran=true;
break;
}
}
if(!bran==true) {
System.out.println("Sales doesn't have " +brand);
}
}
}
}
import java.util.Scanner ;
public class ProcessNumbers
{
public static void main( String[] args )
{
Scanner in = new Scanner(System.in) ;
System.out.print("Please enter an integer between 6 and 12, inclusive: ") ;
int num = in.nextInt() ;
boolean result = shouldProcess(num);
String result1 = String.valueOf(result) ;
}
public static boolean shouldProcess(int n)
{
if (n>=6 && n<12)
{
return true;
}
else
{
return false;
}
}
public static boolean processInput(boolean result2)
{
if (result2 == true)
{
System.out.println("Yes") ;
}
else
{
System.out.println("No") ;
}
return result2 ;
}
}
now I am getting the output which is partially right but has forgot the yes or no output in the second method
Please enter an integer between 6 and 12, inclusive:
when it should also include the yes or not output
You are sending in a boolean value in the method parameter of processInput but you are catching it as a String. You need to change it to boolean. Further, you want to check if its value is true with equal signs like below:
public static void processInput(boolean result2)
{
if (result2 == true)
{
System.out.println("Yes") ;
}
else
{
System.out.println("No") ;
}
}
EDIT 2:
Also, you need to change String result1 = String.valueOf(result); to processInput(result);
EDIT 3:
If you want the number printed too that you just entered and then you want a "yes" or "no", then between int num = in.nextInt(); and boolean result = shouldProcess(num);, add this line: System.out.println(num);
There's apparently some code missing, so I'm guessing this is just part of the full thing. So I will only tackle your output issue.
I won't talk about the code in: public static boolean processInput(boolean result2), because you're not running it anywhere in your main method public static void main( String[] args ) anyway.
Now, in your code at:
public static boolean shouldProcess(int n)
if you look at your code, you are assigning the value of the boolean to the new String result1, so result1 now has the new value, but you are not running its output anywhere, so there's no way the program can guess you want to output that value. You need to assign the output:
System.out.print(result1);
However, if you only want to output the boolean, there's no need to assign that boolean value to a new String and then output the new String, you could just:
System.out.print(result);
Unless you're going to use that value somewhere else where creating a new variable would arguably be a good choice.
Also, it seems you want to return either a "Yes" or "No" on your class: public static boolean processInput(boolean result2).
Remember a class that does not return a value, but rather executes a code, has to be written as void. In other words, your:
public static boolean processInput(boolean result2)
should really be:
public static void processInput(boolean result2)
Because if not, you are just making your program return result2;, which in this case can only be either true or false. By adding void to the class, makes the class understand it will be executing your System.out.print code, rather than returning a value for you to use. But also, depends on what you want to afterwards.
This question already has answers here:
Java exception handling
(8 answers)
Closed 7 years ago.
Well im really new to java and im really trying hard to understand what can be done in java and what can't. I'm making a console application based on the well known game Hangman. Basiclay what i'am trying to do is stop the user from typing 'e's more than twice, to do that i made 2 methods:
The first one adds 1 to the int variable mManyTimes whenever the user types e.
public boolean adder() {
boolean tooMuch = letter == 'e';
if(tooMuch) {
mManyTimes ++;
}
return tooMuch;
}
the second method is the one that sends an exception
to the user when the user types e more then twice.
public void cheatStopper() {
if(mManyTimes == 3) {
throw new IllegalArgumentException("You cant type more Es");
}
}
Basicly i created two files, one that holds the code of the game(Which those two methods are in) and other one.
the file that holds the logic of the game is Game.java and here is the code that is inside it:
public class Game {
private String mAnswer;
private String mHits;
private String mMisses;
private int mManyTimes;
public char letter;
public Game(String answer) {
mAnswer = answer;
mHits = "";
mMisses = "";
}
public boolean applyGuess(char letter) {
//checks for char letter inside the mAnswer variable.
//If it is there the indexOf() method should return the index of the letter.
//If it is not there it will return -1.
//We are basicly saing if indexOf() method returns 0 or more then that then the isHit
//if it is not then the isHit boolean will return false.
boolean isHit = mAnswer.indexOf(letter) >= 0;
if (isHit) {
mHits = mHits + letter;
} else {
mMisses = mMisses + letter;
}
adder();
return isHit;
}
public boolean adder() {
boolean tooMuch = letter == 'e';
if(tooMuch) {
mManyTimes ++;
}
return tooMuch;
}
public void cheatStopper() {
if(mManyTimes == 3) {
throw new IllegalArgumentException("You cant type more Es");
}
}
The other file that holds the main() method and prints the code to the console is Hangman.java:
public class Hangman {
public static void main(String[] args) {
// Enter amazing code here:
Game game = new Game("treehouse");
game.applyGuess('e');
game.applyGuess('e');
System.out.println(game.cheatStopper());
}
}
So here is the question that frustrated me and i never found and answer for:
How do i get my code to work and stop the user from typing more then two e.
Well well i know my code has many errors and bad structure but dont forget that im new to java, and thanks for advance :).
You need a catch block. Look up how to catch exceptions.
I am interested in a very simple string verification problem to see if the starting character in a string starts with an upper case letter and then have the console to display true or false. From my understanding you wouldn't have to invoke something like System.console().printf("true", s) in order to make this happen. I could swear I've seen similar elementary implementations achieved using the following sample code:
public class Verify {
public static boolean checkStartChar(String s) {
if (s.startsWith("[A-Z]")) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
String str = "abCD";
checkStartChar(str);
}
}
but when I run this, nothing displays. If I make a slight modification by adding in conditional printouts before returning T/F, e.g.
public class Verify2 {
public static boolean checkStartChar(String s) {
if (s.startsWith("[A-Z]")) {
System.out.println("yep");
return true;
}
else {
System.out.println("nope");
return false;
}
}
public static void main(String[] args) {
String str = "abCD";
checkStartChar(str);
}
}
the issue is somewhat resolved, as the console displays either "yep" or "nope", yet unresolved because I just want the console to display true or false. That's it. Advice?
As the question has already been answered, I'd like to point out there is no need for RegExes to solve this (and they are expensive operations). You could do it simply like this:
static boolean startsWithUpperCase(String toCheck)
{
if(toCheck != null && !toCheck.isEmpty())
{
return Character.isUpperCase(toCheck.charAt(0));
}
return false;
}
yet unresolved because I just want the console to display true or false
Calling checkStartChar method will return value, that doesn't mean it will print value to console. You need to code how you would like to handle return value. If you want to print return value, then you should do:
System.out.println(checkStartChar(str));
Will print what ever the return of checkStartChar method
if(s.startsWith("[A-Z]")){
String.startsWith(prefix) doesn't take regex as a parameter, you should be using regex APi instead.
Pattern p = Pattern.compile("[A-Z]");
Matcher m = p.matcher(new Character(s.charAt(0)).toString());
if(m.find()){
return true;
}else{
return false;
}
String str = "AbCD";
System.out.println(checkStartChar(str));
Output:
true
In your code checkStartChar(str); is returning a boolean value which is not being used in your program.Then if you want to display true or false then you can use.
System.out.println(checkStartChar(str));