import java.util.Scanner;
class Practice {
public static void main(String args[]) {
System.out.println("Enter the number of treats you have:");
Scanner treatsScanner = new Scanner(System.in);
int treats = (treatsScanner.nextInt());
System.out.println("Enter the number of hamsters you have:");
Scanner hamstersScanner = new Scanner(System.in);
int hamsters = (hamstersScanner.nextInt());
System.out.println("How many treats does each hamster need?");
Scanner neededTreatsScanner = new Scanner(System.in);
int neededTreats = (neededTreatsScanner.nextInt());
int treatsPerHamster = treats / hamsters;
boolean enoughTreats = treatsPerHamster >= neededTreats;
if (enoughTreats = true) {
System.out.println("There are enough treats for all the hamsters!");
}
else if (enoughTreats = false) {
System.out.println("Oh no! There aren't enough treats!");
}
}
}
Can someone explain to me why this program returns "There are enough treats for all the hamsters!" regardless of whether "neededTreats" > "treatsPerHamster"?
Thank you.
You should use == instead of =
if (enoughTreats == true) {
System.out.println("There are enough treats for all the hamsters!");
}
else {
System.out.println("Oh no! There aren't enough treats!");
}
Remember that == is the comparison operator and = is the assignment operator.
And as Mike mentioned, just having if(enoughTreats) will do the trick for you. No need to use == operator!
As a matter of fact, you don't need the boolean variable enoughTreats at all. You could just write your condition like so:
if (treatsPerHamster >= neededTreats) {
// do one thing
}
else {
// do other
}
You are assigning the value true to enoughtreats.
Try using the equality operator rather than assignment:
if (enoughtreats == true) {
...
}
or simply:
if(enoughtreats) {
...
}
In java, the '=' operator assigns a value to a variable. In this case,
if (enoughTreats = true)
assigns the value 'true' to 'enoughTreats' and then checks if 'enoughTreats' is true (which it always will be).
Instead, you want to put
if (enoughTreats == true)
so that it will check if enoughTreats is true or false.
Use == for equality, not =.
if (enoughTreats = true)
By using =, you are assigning true to enoughTreats. Use the == comparison operator instead.
You need to change these two statements
if (enoughTreats = true)
else if (enoughTreats = false)
into
if (enoughTreats == true)
else if (enoughTreats == false)
You could also shorten the code and get the exact same effect by simply typing this below:
if (enoughTreats)
else
If you put a boolean variable inside of the parenthesis of an if statement by itself, the if statement will check to see if it's true, thus you wouldn't need to type '== true.' You could also replace the else if statement in your code with a simple 'else' because if the enoughTreats variable is not equal to true, the else code will automatically execute without you having to specifically state a condition.
Few things to note and to add to the listed answers
Just one scanner is enough Scanner inputScanner = new Scanner(System.in);
Braces around (...Scanner.nextInt()); is not really necessary
You may need to consider a non zero check for hamsters !
Handle Non Ints & -ve numbers in the input
else if(){} is not required when if(){} has only single boolean check , just an else{ is sufficient
Related
So I am trying to validate whether the user typed in a Yes or No and to continue asking until they type in one or the other. This is my code so far.
System.out.println("Would you like a Diamond instead of a Pyramid? Type Yes or No");
String input2 = scan.nextLine();
boolean d = input2.equals("Yes");
System.out.println(d);
while ((d != false) || (d != true)) {
System.out.println("Invalid Input. Please try again");
input2 = scan.nextLine();
d = input2.equals("Yes");
System.out.println(d);
}
Where am I going wrong? I am new to java. Any help would be greatly appreciated.
Edit: I am awful at writing. What I am going for is this type of logic.
Ask the user if they would like a diamond instead of a pyramid.
a. The user must type “Yes” or “No”.
b. If the user types neither of these, ask again until they provide appropriate input.
You are ending up having an infinite loop at
while ((d != false) || (d != true))
since d being a boolean even when updated would either be true or false and in both the cases would satisfy the above condition. Instead you can change it to
System.out.println("Would you like a Diamond instead of a Pyramid? Type Yes or No");
String input2 = scan.nextLine();
boolean d = input2.equalsIgnoreCase("Yes") || input.equalsIgnoreCase("No"); // confirms if the user input is Yes/No or invalid other than that
....
while (!d) { // d==false ' invalid user input
System.out.println("Invalid Input. Please try again");
input2 = scan.nextLine();
d = input2.equalsIgnoreCase("Yes") || input.equalsIgnoreCase("No");
System.out.println(d);
// also printing a boolean would print either true or false base on your input; you migt want to perform some other action
} // this would exit on user input "Yes"
Booleans can ONLY equate to true or false so your while loop is going to execute no matter what because d will be true or it will be false. I think you want to just do
while (d != true)
You are using or(||) operator in your conditions whenever user typed one of your condition is false and other is true so that's why its not working fine.
if you want to stop asking at true value write below condition.
while(d != true)
I am aware that this questions has been asked before, but I still face the same issue after trying to resolve it. Here's the code and an image:
import java.util.Scanner;
class Testing {
public static void main(String[] args){
Greeting();
AgeVerification();
Calculator();
}
static void Greeting(){
System.out.println("Hey. I'm Java, you are...?");
Scanner getname = new Scanner(System.in);
String name = getname.next();
System.out.println("Nice to meet you "+name+".\n");
}
static void AgeVerification(){
System.out.println("How old are you?");
Scanner getage = new Scanner(System.in);
Int age = getage.next();
if(age => 18){
System.out.println("Access granted, go ahead.");
}
else {
System.out.println("Access denied, you're still a minor.");
}
}
static void Calculator(){
System.out.println("Now lets do some maths. Do you want to add, subtract, multiply, or divide?");
Scanner getoperation = new Scanner(System.in);
String operation = getoperation.next();
if(operation == "add" | operation == "Add"){
System.out.println("Which two numbers would you like to add? Enter them separately.");
}
}
}
https://ctrlv.cz/3JDJ
I originally had the three methods below the main listed as public, but removed the "public" attributes only to encounter the same issue. I am new to Java programming, and appreciate the help.
There's a couple of problems with your code.
First, on this line:
Int age = getage.next();
To declare an integer, use the int type. Also, you probably want to use nextInt() instead of next().
Next, this check is the wrong way around:
if(age => 18){
It should be if (age >= 18){.
And finally, in this line:
if(operation == "add" | operation == "Add"){
| is not doing what you think it is here, you should use ||.
As pointed out in the comments, you should check string equality using the equals() method.
if(operation.equals("add") || operation.equals("Add")){
Finally, and this is just nitpicky, but if you wanted to you could change this if-statement to just check:
if (operation.equalsIgnoreCase("add")) {
Hope this helped!
In AgeVerification(), change
Int age = getage.next();
to
int age = getage.nextInt();
Next there is no => opertor in java. So to compare the age change
if(age => 18){
System.out.println("Access granted, go ahead.");
}
to
if(age >= 18){
System.out.println("Access granted, go ahead.");
}
Also, you can " | " refers to bitwise OR. Whereas you want to check if the string equals add or Add. So change it to
if(operation.equalsIgnoreCase("add")){
System.out.println("Which two numbers would you like to add? Enter them separately.");
}
You should change this:
Int age = getage.next();
to:
int age = getage.nextInt();
Case is important in Java, and while int is a built-in primitive type, Int has no meaning unless you define your own class called Int (which it seems you have not done). That will get rid of the "Illegal start of expression error". However, it will give you a different error because Scanner#next() returns a String and you want an integer value. Thus, you should be calling nextInt() instead of next().
Also, as others have pointed out, the integer comparison operator you want to use in the next line is >= (think "greater than or equal"); there is no => operator in Java.
I have a lab that I have to do for my computer class and i have an error that I can't seem to figure out. I get the error on the first if statement, if(something.indexOf(x) = "a"). I want to change the other if statements to be of that form.
The error I get is:
unexpected type
required:variable: found; value
Scanner in = new Scanner(System.in);
String[] input = new String[1000];
String[] output = new String[1000];
int x = 0;// All purpose counter
int y = 0;//Second purpose counter
boolean ends = false;
boolean starts = false;
/**
* This method is supposed to take the dna array and create an rna array from it to return
* to the main method wherever this method is called.
*
* #param String[] input The array that contains the dna sequence
* #return String[] output The array that contains the mRNA we just created in this method
*/
public void makeRNA()
{
System.out.println("Enter a simple DNA Sequence, make sure the amount of variables are a multiple of 3.");
String something = in.nextLine();
while(x < 1000)
{
if(something.indexOf(x) = "a")
{
output[x] = "u";
}
else if(input[x] == "c")
{
output[x] = "g";
}
else if(input[x] == "g")
{
output[x] = "c";
}
else if(input[x] == "t")
{
output[x] = "a";
}
x++;
}
for(x = 0 ; x < 1000; x++)
{
System.out.println(output[x]);
}
}
The problem seems to be here: if(something.indexOf(x) = "a")
To get the character at index x you need to use charAt().
Instead of the assignment operator, you need to use == (comparison operator).
Compare it with a char and not a String, because charAt() returns a char. So change "a" to 'a'.
So your statement should finally look like:
if(something.charAt(x) == 'a')
if(something.indexOf(x) = "a") ,= is assignment operator. you need == operator in your if statement unless the assignment results in a boolean.
also, indexOf() returns an int ,so you can't use == with "a", use equals() for string comparison.
java if statement doesn't work like c or c++.
Ramanlfc is correct in saying use == instead of = because just a single equals sign is an assignment operator.
However, I'm not sure your IF statements are doing what you want them to do. The indexOf() method returns an integer and you're trying to compare it to a string, an object, using == (equals). If you want to compare two strings use the .Equals() method. You cannot use == on an object, which is what a string is. However, you can use == on chars because they are primitive types. To specify a char use single quotes not double quotes (double quotes specifies a string which is currently how you have your if statement set up). I'm assuming java will use the hex value of the char to compare it to a number. Once again, I'm not sure what you're trying to achieve, but just some helpful advice!
I'm assuming you want something like the following:
if(stringMsg.charAt(INDEXVALUE) == 'a')
This gets the character at the specified value in the string and checks to see if it is the same (equal to) the char a. Remember characters in a string are number 0 to (length - 1).
The problem is this line of code:
if(something.indexOf(x) = "a") // it should be "==" instead of "="
The correct code is:
if(something.indexOf(x) == "a")
Please note that if(something.indexOf(x) = "a") will always return true in java.
I'm making a program with Java that needs to involve some error checking. I can stop users from entering bad numerical inputs like this (assume the input scanner has already been created):
while (n == 0){
System.out.println("Can't use 0 as a denominator! Please enter a real, nonzero number");
n = input.nextInt();
}
But how do I stop users from entering an invalid string? I can't use !=, because strings can only be compared with the string.equals() method, right? So, is there a while not loop? ie:
while !(string.equals("y") || string.equals("n")){
//here have code
}
Or something of that nature?
While there is no such thing as a while-not loop, you can always invert the condition:
while (!(string.equals("y") || string.equals("n"))){
This is read, "while the string is not equal to "y" or "n"".
You could also apply DeMorgan's identity to rewrite this as:
while (!(string.equals("y")) && !(string.equals("n"))){
which is a bit clearer as "While the string isn't equal to "y" and isn't equal to "n"".
There isn't a while-not instruction, but you can simply negate the condition in a normal while loop. Try this:
while (!string.equals("y") && !string.equals("n"))
Or even better, to guard against the case where the string is null and/or it's in a different case:
while (!"y".equalsIgnoreCase(string) && !"n".equalsIgnoreCase(string))
You almost get it, just change where you position your !
like this:
while (!(string.equals("y") || string.equals("n")))
Why not try regex?
Scanner sc = new Scanner(System.in);
String string = sc.nextLine();
while (!string.matches("(?i)^(?:y|n|yes|no)$"))
{
System.out.println("Invalid input...");
string = sc.nextLine();
}
boolean answer = string.matches("(?i)^(?:y|yes)$");
What is the mistake in the following code?
while ((char t==(char) System.in.read())!='0')
You can not declare a new variable in a while loop.
while (boolean always = true) {
} // DOES NOT COMPILE!!!
You'd have to declare the variable before and outside of the loop, so perhaps something like this:
boolean always = true;
while (always) {
break;
} // compiles fine!
// always is still in scope after the loop!
always = !always;
In this sense, for loop is unique: you can in fact declare a new local variable whose scope is limited to that loop:
for (boolean always = true; always; ) {
break;
} // compiles fine!
// always is no longer declared after the loop!
always = !always; // DOES NOT COMPILE!
That said, looking at what you're doing, you may want to look at java.util.Scanner. I suspect that it will serve your need much better.
Example
Here's an example of using Scanner to read numbers from standard input, terminating at 0. It then prints the sum of those numbers. It handles invalid input gracefully using hasNextInt() instead of Integer.parseInt/NumberFormatException.
Scanner sc = new Scanner(System.in);
System.out.println("Enter numbers (0 to end):");
int sum = 0;
int number;
do {
while (!sc.hasNextInt()) {
System.out.println("I'm sorry, that's not a number! Try again!");
sc.next();
}
number = sc.nextInt();
sum += number;
} while (number != 0);
System.out.println("The sum of those numbers is " + sum);
Here's an example session:
Enter numbers (0 to end):
1
3
-1
five
I'm sorry, that's not a number! Try again!
2
0
The sum of those numbers is 5
This is probably what you intended to write.
char t;
while ((t = (char) System.in.read()) != '0') {
//...
}
while ((char t==(char) System.in.read())!='0')
// ^^ should be 'char t = ...'
This loop can be rewritten more clearly as
while (true) {
char t = (char) System.in.read();
if (t == '0')
break;
...
char t is a statement which declares a variable rather than an expression; it has no value to compare with the == operator. You probably also meant to use assignment rather than equality, but unlike C++ the declaration does not have a value.
The easiest way of restricting the scope of a variable in a loop is to use for instead, which specifically allows you to declare variables.
for (char t; ( t = (char) System.in.read() ) != '0'; )
// loop body involving t
However, some company's guidelines don't allow mutating operators in boolean expressions, such as the read and the assignment, and would prefer you to separate them out onto several lines. Personally I find restricting the scope more important.