First of all, I apologize for this unclear title!
So I am making an app, and I have an if statement :
if(num.contains(input) )
{
...
}
So, say num is 213, and input is 1, it will still execute the the block inside the statement.
But I want to make an if statement that only executes when num starts with input, and the other characters after 1 don't matter.
Note:
All variables are Strings
you can use startsWith()
num.startsWith(input)
Here is something for your reference :-
https://www.tutorialspoint.com/java/java_string_startswith.htm
maybe convert it to a string and see if the index of input is in the string at the very front.
if(String.valueOf(num).indexOf(String.valueOf(input))==0){
//do stuff
}
edit:
If the variables are strings you can just check the index of input in num
if(num.indexOf(input)==0){
//do stuff
}
Related
There is probably an obvious answer. This question might have already been asked but I don't know how to word the question. I'm working in Java and in this moment, I am reading the input text from the command line and converting that stuff over to strings.
I am, for sure, inputting the x character into the command line and whether I set the code to
!(first.equals("x")) or (first.equals("x"))
I still get the system.out output text. I noticed that if I remove the || and the following equals snippet it works as intended and continues onto the code. However, I have to have either x or y be options for the first arg string. Can someone please let me know what I am doing wrong. Thanks.
Here is the snippet of code:
private something(String[] args)
{
first = args[0];
second = args[1];
third = args[2];
if (!(first.equals("x")) || !(first.equals("y")))
{
System.out.println("First is the problem " + first);
}
}
Here is the ouput:
First is the problem x
Edit: I also did this and got the same result:
if (first.equals("x") == false || first.equals("y") == false)
{
System.out.println("First is the problem " + first);
}
I'm using this if-statement as a check for whether or not the two values are inputted. If they aren't then the if-statement should trigger.
It works when I have it like this, but I end up losing the y:
if (first.equals("x") == false)
{
System.out.println("First is the problem " + first);
}
first is either NOT "x" or NOT "y". This will always be true for whatever string first is set.
=> Are you not republican or are you not democrat? ;)
This code appears to work. The if statement returns as true if args[0] equals either x or y. !(first.equals("x")) means that it is true for every string except "x", so this would do the opposite of what you want. Also, you need to define first, second, and third otherwise it won't compile.
Edit:
Looking at your edit, it appears the issue is caused by ||. Since this means 'or', first only has to not equal either x or y for the if statement to run. Therefore, since it can't equal both at once, the if statement will always run. You should use &&(and) instead. Also, notice that == false can be replaced with !.
For example:
if (!(first.equals("x")) && !(first.equals("y")))
{
System.out.println("First is the problem " + first);
}
Dear Stackoverflow community I am Struggling with one task on repl.it (018) Conditional Statements 4
So they want me to do that :
Instructions from your teacher:
For you to do:
Given a string variable "word", do the following tests
If the word ends in "y", print "-ies"
If the word ends in "ey", print "-eys"
If the word ends in "ife", print "-ives"
If none of the above is true, print "-s"
No more than one should be printed.
and my code looks like this :
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
System.out.print("In:");
String word = inp.nextLine();
//DO NOT CHANGE ABOVE CODE! Write your code below
if(word.endsWith("y"){
System.out.println("-ies");
}
else if(word.endsWith("ey")){
System.out.println("-eys");
}
else if(word.endsWith("ife")){
System.out.println("-ives");
}
else{
System.out.println("-s");
}
}
}
When I run it for example my input is :Hey
and of course my code will go through the code and see if the first statement is correct and yes it is equal because y = y at the end and that is WRONG!
My question is how can i let my code compare the last 2 or 3 characters so it will print out the right value when I input Hey.
If I input Hey it should print out :
-eys and not -ies
Ty
Since ending with "ey" is a subset of ending with "y", your 2nd if will never be true.
Change the order of your tests to the most specific first:
if(word.endsWith("ey"){
System.out.println("-eys");
}
else if(word.endsWith("y")){
System.out.println("-ies");
}
else if(word.endsWith("ife")){
System.out.println("-ives");
}
reorder the conditions as such:
if(word.endsWith("ey")){
System.out.println("-eys");
}
else if(word.endsWith("ife")){
System.out.println("-ives");
}
else if(word.endsWith("y")){
System.out.println("-ies");
}
else{
System.out.println("-s");
}
This means we hoist the condition that is most specific and put the less specific ones below.
I've put the else if(word.endsWith("y")) as the last of the else ifs but it really doesn't matter where within the else if chaining you put it as long as it's before the condition if(word.endsWith("ey")) things should be fine.
Fairly new to java and programming.
Wrote this recursive method, with the objective of asking for a valid string that is both an integer and greater than 0:
private int getDimension(String tableElement){
Integer Input= 0;
System.out.println("Define table rows "+tableElement+"'s."
+"Enter an integer >= 1:");
if( !Reader.hasNextInt() || (Input=Input.parseInt(Reader.nextLine())) <= 0)
return getDimension(tableElement);
return Input;
}
I'd like to stick to using a short and recursive method. It seems to handle the >= 0 logic fine, but blows up when i pass it something other than an integer.
Can someone explain why does that happen to me please?
hasNextInt() doesn't actually consume your input, so you're stuck with the same non-int input on your next call.
Simply spoken, your code doesn't make much (any?) sense.
First of all, there is not really a point in using a recursive method that asks the user for input; and that does not at all do anything about the argument passed to it!
private int getDimension(String tableElement){
Integer Input= 0;
Bad: you keep up mixing int and `Integer. They are not the same. And - read about java coding style guides. Variable names start lower case!
if( !Reader.hasNextInt() || (Input=Input.parseInt(Reader.nextLine())) <= 0)
The first condition gives:
true: when there is NO int ...
false: when there is an int
true leads to: calling your method again without retrieving a value from the reader.
false leads to parsing an int; and checking its value for <= 0.
In one case, you are doing a recursive call; completely ignoring the input you got from the reader; in the other case, you returning 0; or that value in input.
Solution: do something like:
while (true) {
if (reader.hasNextInt()) {
input = reader.nextInt();
break;
}
// there is no number!
read.nextLine(); // consume & throw away non-number!
print "Enter a number"
}
instead.
But seriously: start with throwing away this code.
Final side note: you do Input.parseInt() ... but that is a static method on the Integer class. Just call that as Integer.parseInt() instead! But as said; throw away your code; and learn how to properly use that Scanner class; start reading here.
Because the user can enter anything, you must always read in the line, then compare it:
String num = Reader.nextLine();
return num.matches("[1-9][0-9]*") ? Integer.parseInt(num) : getDimension(tableElement);
Here I've use regex to figure out if it's a positive number; the expression means "a 1-9 char followed by 0 or more of 0-9 chars"
I'm trying to learn java but I'm stuck trying to do a single program which concerns Do While Statement with two conditions. Specifically, I want a method to run until the user write "yes" or "no". Well, down there is my thing, what is wrong with it?
String answerString;
Scanner user_input = new Scanner(System.in);
System.out.println("Do you want a cookie? ");
do{
answerString = user_input.next();
if(answerString.equalsIgnoreCase("yes")){
System.out.println("You want a cookie.");
}else if(answerString.equalsIgnoreCase("no")){
System.out.println("You don't want a cookie.");
}else{
System.out.println("Answer by saying 'yes' or 'no'");
}while(user_input == 'yes' || user_input == 'no');
}
}}
I'd do something similar to Tim's answer. But to do things the way you were trying to do them, you have a lot of problems that need to be fixed:
(1) String literals in Java are surrounded by double quote marks, not single quote marks.
(2) user_input is a Scanner. You can't compare a scanner to a string. You can only compare a String to another String. So you should be using answerString in your comparison, not user_input.
(3) Never use == to compare strings. StackOverflow has 953,235 Java questions, and approximately 826,102 of those involve someone trying to use == to compare strings. (OK, that's a slight exaggeration.) Use the equals method: string1.equals(string2).
(4) When you write a do-while loop, the syntax is do, followed by {, followed by the code in the loop, followed by }, followed by while(condition);. It looks like you put the last } in the wrong place. The } just before the while belongs to the else, so that doesn't count; you need another } before while, not after it.
(5) I think you were trying to write a loop that keeps going if the input isn't yes or no. Instead, you did the opposite: you wrote a loop that keeps going as long as the input is yes or no. Your while condition should look something like
while (!(answerString.equals("yes") || answerString.equals("no")));
[Actually, it should be equalsIgnoreCase to be consistent with the rest of the code.] ! means "not" here, and note that I had to put the whole expression in parentheses after the !, otherwise the ! would have applied only to the first part of the expression. If you're trying to write a loop that does "Loop until blah-blah-blah", you have to write it as "Loop while ! (blah-blah-blah)".
I might opt for a do loop which will continue to take in command line user input until he enters a "yes" or "no" answer, at which point the loop breaks.
do {
answerString = user_input.next();
if ("yes".equalsIgnoreCase(answerString)) {
System.out.println("You want a cookie.");
break;
} else if ("no".equalsIgnoreCase(answerString)) {
System.out.println("You don't want a cookie.");
break;
} else {
System.out.println("Answer by saying 'yes' or 'no'");
}
} while(true);
This is an assignment i have to complete.
Can someone lead me in the right direction?
The program compiles but wont run correctly.
The error is InputMissmatch exception.
The error you are getting means that you are trying to use some kind of data as another one, in your case, you are probably trying to use a String as a float.
When using any of the next methods in the Scanner class you should first be sure that there's an appropiate input from the user.
In order to do so, you need to use the has methods.
Your problem is that you are not checking wether the input is a correct float or not before using your Scanner.nextFloat();
You should do something like this:
if (hope.hasNextFloat())
{
// Code to execute when you have a proper float,
// which you can retrieve with hope.nextFloat()
}
else
{
// Code to execute when the user input is not a float
// Here you should treat it properly, maybe asking for new input
}
That should be enough to point you in the right direction.
Also, check the Scanner api documentation for further details.
EDIT
Also, you are asking the user to input characters (or strings): "A", "B", etc..., but you are trying to compare them with a float. That's wrong, you should compare them with a string or character, like this:
if (hope.hasNextString())
{
if (hope.nextString().equals("A"))
{
// Code for option "A"
}
else if (hope.nextString().equals("B"))
{
// Code for option "B"
}
else ...
}
You could use a switch there, but it seems that you are not yet very fammiliar with java, so I'll leave it for another time.
Your problem is that you are entering a letter into a float field.
In your program you're asking the user to enter a float:
A = hope.nextFloat();
But if you enter the letter "A", you're going to get an exception because "A" is not a float, it's a string.
A simpler way to solve your problem is instead of having all the choices fields, you just read the input the user enters from the scanner like:
String choice = hope.next();
Next in the if statement, you check if the value from the string choice is equal to a specific letter, for example
if (choice.equals("A")) {
number4 = (number1 + number2 + number3);
System.out.printf("Your results are:" + (number4));
}
And you can do the same thing for the other choices you have.