I am not sure what to do but I can't print anything with this. I am beginner in programming and kind of lost right now.
So the question is what I need to put in the String integer = ""; to make this print something? I am using java. Thanks for help.
package myproject;
public class broke {
public static void main(String[] args){
boolean success = false;
String integer = "";
if(integer.indexOf("2") == 3){
success = true;
}
if(success){
System.out.println(integer);
}
}
}
Any string which has 2 at index, 3 will make the condition, integer.indexOf("2") == 3 true. Note that the index starts from 0 in a string.
Demo:
public class Main {
public static void main(String[] args) {
boolean success = false;
String integer = "543210";
if (integer.indexOf("2") == 3) {
success = true;
}
if (success) {
System.out.println(integer);
}
}
}
Output:
543210
In the string, 543210, the index of 5 is 0 and starting with this index, the index of 2 is 3.
your program will only print when success is true, since the statement, if(integer.indexOf("2") == 3) is false(integer is empty), success will be false, thus System.out.println(integer); will not be executed.
You're creating a String variable called "integer", and setting it's value to "" (an empty string).
System.out.println(integer);
The above snippet, if not for the weird if statement.. would print your string.. but your string is empty, so that printing would just consist of a \n being sent to System.out.
The reason nothing is printing is because the method call "string.indexOf("2")" returns -1 (indicating the character "2" was not found).
I saw in your comment you tried this with the string "3333", and again, expectedly, the character "2" would not be found.
I ran your code with setting String integer = "2", and it worked fine.
Maybe your confusion is how the indexOf() method, belonging to the String class, works. It returns the first index where the value passed in as a parameter occurs.
Related
trying to check if the letters of the word are sorted alphabetically.but i don't get any return from the method.
import java.util.Scanner;
public class A284 {
//Write a Java program to check
// if each letter of a given word (Abecadrian word) is less than the one before it.
public static boolean abecidarianWord(String word){
int index=word.length()-1;
for(int i=0;i<index;i++){
if (word.charAt(i)<=word.charAt(i+1)){
return true;
}else return false;
}
return true;
}
public static void main(String[] args) {
String entry;
System.out.println("input a word: ");
Scanner s1=new Scanner(System.in);
entry=s1.next();
abecidarianWord(entry);
}
}
You have two problems here.
First, you're not using the value returned from abecidarianWord, you're just calling it and ignoring the result, so you have no way of knowing what the method will return. So you should assign the return value to a variable and do something with it. For example, at the end of your main a naive implementation would do something like:
boolean isOrdered = abecidarianWord(entry);
if (isOrdered) {
System.out.println("String is ordered");
} else {
System.out.println("String is not ordered");
}
Second, in abecidarianWord you're returning immediately after the first iteration of the loop, which will only tell you if your condition holds true for the first two characters.
Instead you may want to return false as soon as you find a pair that doesn't respect the condition and return true if you reach the end of the loop without "accidents", so something like:
public static boolean abecidarianWord(String word) {
for (int i=0; i < word.length -1; i++) {
if (word.charAt(i) > word.charAt(i+1)) {
return false;
}
}
return true;
}
You have successfully returned the value.
import java.util.Scanner;
public class A284 {
public static boolean abecidarianWord(String word){
//you are getting length of "word" here
int index=word.length()-1;
for(int i=0;i<index;i++){
if (word.charAt(i)<=word.charAt(i+1)){
//If condition are correct return true.
return true;
}else{
//If condition are incorrect return false
return false;
}
}
return true;
}
public static void main(String[] args) {
String entry;
//Printing a text
System.out.println("input a word: ");
//getting values from user
Scanner s1=new Scanner(System.in);
entry=s1.next();
//calling a class
abecidarianWord(entry);
//You have get the value. But, you are actually trying to say that why it's not printing in output. When you return something you have to put them in another function to print-out
System.out.println(abecidarianWord(entry));
//If you don't wanna do it than you have to write SOUT instead of return. Than you can output the way you wrote
}
}
You are returning true on first comparison, so your loop only runs once. Instead, change your if condition inside for loop as below.
if (word.charAt(i)>word.charAt(i+1)){
return false;
}
#Istiak is perfectly right.
But just for optimizing your code to do what I think you would ideally want, I just wanted to say that the if statement -> if (word.charAt(i)<=word.charAt(i+1)) iterates for every two charecters in the word and you don't want to return true if just two letters are in order, Ideally replace return true; with just an empty ; otherwise your function will stop immediately after it finds a pair of two consecutive correctly placed letters.
The compiler keeps telling to return string.I used if-else condition and from within if-else i have returned string.The compiler problem will be solved if i put return statement at the end of the code but my problem will start .I dont understand how to solve this problem.I want to return right when its right.
Code:
public String isValidID(String id) {
if(getId().length()!=6) {//checks for 6 digit id
return "wrong";
}
else{//checks if digit contains invalid entry
for(int i=0;i<getId().length();i++){
if(Id.charAt(i)>'9'||Id.charAt(i)<'0')
return "wrong";
}
}
}
In reply to my comment to add return "right" at the end, you said:
but that will make the program return "right " always.Becoz after if-else condition check ,the compiler will execute rest statement and will return "right" always
Now the source of your confusion is clear: return doesn't just set the value the method will return, it also exits the method, immediately. So for instance, the return "wrong"; inside your loop will exit from the loop, and the method, immediately. This is true of all the languages I've seen that use the return keyword (whereas there are some languages, like VB/VB.Net, where you assign a value to the function's name to set the return value, but execution continues normally until you use "exit").
That's why adding return "right"; at the end is how you resolve this, because the code won't reach that point if it ever reached return "wrong"; during the program flow above it:
public String isValidID(String id) {
if(getId().length()!=6) {//checks for 6 digit id
return "wrong"; // <== Exits immediately if reached
}
else{//checks if digit contains invalid entry
for(int i=0;i<getId().length();i++){
if(Id.charAt(i)>'9'||Id.charAt(i)<'0')
return "wrong"; // <== Exits immediately if reached
}
}
return "right"; // <== Exits immediately if reached
// (granted, we would have exited
// below anyway :-) )
}
In any condition, you need to return "something". In your code it possible that return never executed in a certain condition. Suppose your program execution comes to if(Id.charAt(i)>'9'||Id.charAt(i)<'0') and it never gets true then what the method will return? So, You need to write the code in a manner that in condition method execution will execute a return statement which returns a String object.
Just imagine a conditon Suppose
1. getId().length()!=6 -> false
2. getId().length() is 0
3. for(int i=0;i<getId().length();i++) will never enter the loop.
Then what should the method returns when you call it.
If I can understand your logic you can just use :
public String isValidID(String id) {
return id.matches("\\d{6}") ? "correct" : "wrong";
}
You check the length if it is 6 or not then you check if all characters are digits, you can combine both of them in one instruction, just check if the input is a number with length 6 with regex.
If you want a clean solution use boolean instead of a String in this case you can use :
public boolean isValidID(String id) {
return id.matches("\\d{6}");
}
Inside your else you have another if statement, so your return its not always reached. You need another return after the for cycle.
And you are checking if something is wright or wrong you should return Boolean true or false.
public boolean isValidID(String id) { if(getId().length()!=6) {//checks for 6 digit id return false; }
else{//checks if digit contains invalid entry for(int i=0;i'9'||Id.charAt(i)<'0') return false; }
return true;// when nothing false was found.
}
}
So in your case, I would have done public boolean isValidID instead.
Here, the compiler tells you to return something in case the length of the ID is not correct and the components of the ID (so the caracters) are between 0 and 9 (for example if your ID is something like 00ggg89, then I suppose it is wrong, but if your ID is 000000, then it could be right. Here is what I would have done
public boolean isValidID(String id) {
return id.matches("[0-9]{6}");
}
Hope this helps ! :D
public String isValidID(String id) {
String result = "right";
if(getId().length()!=6) {//checks for 6 digit id
result = "wrong";
}
else{//checks if digit contains invalid entry
for(int i=0;i<getId().length();i++){
if(Id.charAt(i)>'9'||Id.charAt(i)<'0')
result = "wrong";
}
}
return result;
}
Edit: In case the first statement is not valid it will never get to a return statement. Thats why you have to return a String in every possible case.
so I'm a newish Java programmer, and this might just be a concept that went right over my head. but if I am calling a boolean method in a program, such as keepDice2 below, how can I check the return value-true of false- in an if statement? Below is my attempt.
I am attempting to make a method, keepDice2, return the boolean false if the user inputs a String containing 'N' or 'n'. Then, I want to make an if stateent: if the return value is the boolean false, then call the method rollDice2 ( I have not included rollDice2 as it seems irrelevant). ANy insight into this wwould be greatly appreciated!
public static boolean keepDice2() {
Scanner input = new Scanner(System.in);
System.out.println("Keep Dice Two?");
String keepDice = input.nextLine();
boolean answer;
if (keepDice.contains("n") || keepDice.contains("N")) {
answer = false;
//here, if the answer contains n or N, then it is a form of "No", so that dice will be re-rolled.
}
else {
answer = true;
}
return answer;
}
public static void (String[] args) {
if (keepDice2() == false) {
rollDice2();
}
}
keepDice2() returns boolean so you don't need to compare it. You also forgot to name the method which is main
public static void main (String[] args) {
if (!keepDice2()) {
rollDice2();
}
}
What have you written is correct, but you can achieve the same result with less code.
Everything inside one if statement brackets is a boolean expression. So if you want to write code that will run in case this expression returns true you just write this expression in bracket and that's it, if you want it to run in case it returns fals you just put ! in front of it.
Eq:
if(keepDice2()) {
rollDice2();
///////////////////////////////////////////
// put here rest of code you want to run //
// if keepDice2() returns true //
///////////////////////////////////////////
}
/*if keepDice2 returns false.
* But since
* there are only two possible outcomes
* you can just use else statement instead
* if else if with boolean expression in
* brackets
*/
else if (!keepDice2()) {
///////////////////////////////////////////
// put here the code you want to run //
// if keepDice2() returns false //
///////////////////////////////////////////
}
I have an issue where I am trying to compare an object's name (String) to another String, and I've tried using .equals() as well as == but neither seem to work in my case.
The code I have right now is:
public boolean checkingObjectName(String checkName)
{
for (int i=0; i<count; i++) //where 'count' has a value of 3
{
if (product[i].getName().equals(checkName)) //where product[i] has been initialised
{
return true;
}
else
{
return false;
}
}
}
The program always returns false, even if the name that has been set to product[i] is the same as the parameter given. I've tried looking at other questions relating to .equals() and == and other String references but I have not had any luck in finding something that relates to my problem.
I have seen people use compareTo(), but I'm not sure if that is necessary in my code, and I'm not completely sure on how to use it.
EDIT: As said by Houssni in the comments, I have just realised that the return statement ends the loop and method. Is it possible to check each product's name without having the method terminated after the first check, and have it return a boolean value?
EDIT 2: I have modified the code to how the answers that have been provided say, which is:
public boolean checkingObjectName(String checkName)
{
for (int i=0; i<count; i++) //where 'count' has a value of 3
{
if (product[i].getName().equals(checkName)) //where product[i] has been initialised
{
return true;
}
}
return false;
}
I still get the same issue with the product[i].getName() not being equal to checkName and the method returning false, even though they should equal. Any possibilities on why this is happening, because I've looked through my code and I'm not sure.
Edit 3: The only other code that relates to the block of code above is the input of the parameter from another class, which is:
String checkName = JOptionPane.showInputDialog("Enter the name: ");
while (storingProducts.checkingObjectName(checkName) == false) //assume for storingProducts
{
JOptionPane.showMessageDialog(null, "No products were found. Please re-input name.");
checkName = JOptionPane.showInputDialog("Enter the name: ");
storingProducts.checkingObjectName(checkName);
}
if (storingProducts.checkingObjectName(checkName) == true)
//extra code
So, that's all the code relating to my issue. I'm still not sure why the method returns false, though both values are receiving the same String value.
Edit 4: The product and count are coming from the class with the checkingObjectName method:
public class Store
{
private Product[] product; //Product is another class that just sets and gets
private int count=3;
public Store()
{
product = new Product[count];
for (int i=0; i<count; i++)
{
product[i] = new Product();
}
//extra code
SOLUTION
I fixed the issue: instead of using .equals(), I tried using .equalsIgnoreCase() and it worked.
The method is returning as soon as it hits count 0 and it doesn't find a match. If you want to loop through your array until you find a matching name, your code should look like this:
public boolean checkingObjectName(String checkName)
{
for (int i=0; i<count; i++) //where 'count' has a value of 3
{
if (product[i].getName().equals(checkName)) //where product[i] has been initialised
{
return true;
}
}
return false;
}
There are two ways to compare strings:
The first is to compare via addresses of the string. Such as: string blue = string red.
The second way to compare strings is through values. This can be done by using the string.equals("StringValue").
Since you have a return statement that will be reached on every posible situation (if condition is true or false), the method will always exit on the first iteration.
What can you do? If you want to return true if the name exists in the array and false otherwise, you can do:
public boolean checkingObjectName(String checkName)
{
for (int i=0; i<count; i++) //where 'count' has a value of 3
{
if (product[i].getName().equals(checkName))
return true;
}
return false; // if after all elements has been checked
// and none was equal to 'checkName', return 'false'
}
How about collecting the names into a List (or Set) and check if checkName matches?
public boolean checkObjectName(final String checkName) {
List<String> productNames = new ArrayList<String>();
for (Product prod : product) {
productNames.add(prod.getName());
}
return productNames.contains(checkName);
}
Note that this will only work if you're comparing case-sensitive strings. Alternatively,
public boolean checkObjectName(final String checkName) {
List<String> productNames = new ArrayList<String>();
for (Product prod : product) {
productNames.add(prod.getName().toLowerCase());
}
return productNames.contains(checkName.toLowerCase());
}
If you do not like this approach, you can use the ones given already, and replace equals with equalsIgnoreCase.
This is the line I have trouble understanding
return (match(regex.substring(1), s)|| match(regex, s.substring(1)));
My understanding is that it would call the latter if the first method is false. So I wrote an simple program to test.
public static void main(String[] args)
{
System.out.println(test(5));
}
public static boolean test(int a)
{
System.out.println(a);
if (a>10)
return true;
if (a==4)
return false;
else
return (test(a-1) || (test(a+1)));
}
But it just prints 5 4 6 5 4 6...
A logical OR is true if either the left or the right expression is true. If the left expression is true, a computer language can opt not to evaluate the right expression to save time. That is, in fact, exactly what Java does.
That means that
match(regex, s.substring(1))
will be executed if and only if
match(regex.substring(1), s)
is false.
So the return value is:
true if match(regex.substring(1), s) returns true,
the return value of match(regex, s.substring(1) otherwise
It's equivalent to:
if match(regex.substring(1), s) return true;
if match(regex, s.substring(1)) return true;
return false;
The program you wrote calls test with a 5 as a param. This prints the five. This is not bigger than 10 of 4, so it goes to the else. In the else you call it's own method recursively, with a 4 the first time. So the 4 is printed This returns a false. Then it tries the second which is a+1, so it calls test with a 6. This prints the 6 on the screen, falls through to the else, and calls test again recursively, with a (which is now 6) -1 so with a 5. This loop is endless.
You have to put the first if:
if (a==4)
This fixes the program, but not what you want to get.
Also the problem is that you use the logical or completely wrong. An OR is meant to see if one of the both answers is true. If you want to call a method depending on a situation, you have to use an if or a ternary operator.
public static void main(String[] args)
{
System.out.println(test(5));
}
public static boolean test(int a)
{
System.out.println(a);
if (a>10)
return true;
if (a==4)
return false;
else
if(test(a-1)) {
return test(a-1);
}
else {
return (test(a+1));
}
}
This should give you what you want I guess