This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
When I try to use a while loop it won't follow the conditions I set in the while. Like if I put while s1 != "n") it will continue even if s1 = n. It does the opposite when I try to use while s1 == "y") and it very irritating. I'm trying to make a factorial calculator that prompts the user if they would like to keep going or stop.
Here's the full code:
package factorial;
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
int factorial = 1;
int number = 6;
int i = 1;
String s1 = "y";
Scanner keyboard = new Scanner(System.in);
while(s1 != "n") {
System.out.println("Enter an N:");
number = keyboard.nextInt();
while(i <= number) {
factorial *= i;
i++;
}
System.out.println("Factorial = "+factorial);
System.out.println("Would you like to continue? (y/n)");
s1 = keyboard.next();
}
keyboard.close();
System.out.println("Have a nice day!");
}
}
As #Debabrata says use equals for strings, replace:
while(s1 != "n") {
with
while(!s1.equals("n")) {
Related
This question already has answers here:
What is the difference between == and equals() in Java?
(26 answers)
Closed 5 months ago.
I have made a java code to play hangman game. I have given the user 15 chances to guess the word and once the user has guessed the correct answer it should execute the if statement but it does not. I have tried to solve this problem many times but it is never working. I would appreciate it if you could tell me the problem and give a suitable solution without making much change in my code.
My code:
import java.util.*;
public class game
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
String list[] = {"apple", "banana", "mango", "kiwi", "coconut", "papaya", "lichi", "strawberry", "orange", "cherry"};
int rand = (int)(Math.random()*9)+0;
String word = list[rand];
String ask = "_";
for(int i = 1; i < word.length();i++){
ask = ask + "_";
}
System.out.println(ask);
System.out.println("hint: It is a fruit");
ArrayList<String> ans = new ArrayList<String>();
for (char i : ask.toCharArray()){
ans.add("_");
}
for (int j = 1; j<=15; j++){
System.out.println("Enter a character: ");
String input = in.next();
char alt = input.charAt(0);
int x = 0;
for (char i : word.toCharArray()){
if(alt == i){
ans.set(x, input);
}
x++;
}
for (String i : ans){
System.out.print(i);
}
int y = 0;
ArrayList<String> answer = new ArrayList<String>();
for (char i : word.toCharArray()){
answer.add("_");
}
for(char i : word.toCharArray()){
String alternate = String.valueOf(i);
answer.set(y, alternate);
y++;
}
if (ans == answer){
System.out.println("\nyou win");
break;
}
System.out.println("\n"+ans);
System.out.println(answer
);
}
}
}
Due to so many many unsuccessful attempts my code may have some unnecessary lines which are making the long.
when you use == it compares whether these two reference variables are pointing to the same object or not.
if you want to compare their content then you should use the equals() method which compares the content of the object, not the object itself.
use ans.equals(answer) instead of ans== answer
Try using equals() method instead of ==.
if (ans.equals(answer)){
This question already has answers here:
How to break a while loop from an if condition inside the while loop?
(3 answers)
Closed 2 years ago.
//File name: SmallIO.java
import java.util.Scanner;
public class SmallIO{
public static void main(String[] args){
Scanner keyboard = new Scanner (System.in);
String a = ""; // initialise to empty string
while (true){
//an infinite loop, use Ctrl-C (from command prompt) to quit
System.out.println("Enter a line:");
a = keyboard.nextLine();
System.out.println("Your line: " + a);
System.out.println();
}//end of while
}//end of main
}//end of class
There are multiple ways, the simplest one would be to use an actual for loop:
for (int i = 1; i <=5; i++) {....}
This is the same as:
int i = 1;
while (i <= 5) {.... i++; }
To break a loop(any loop), you use the break statement.
To break a loop after 5 iterations, you use a counter
This is one of the way to use a counter in combination with break
int counter = 0;
while(true) {
counter++;
if (counter == 5) break;
}
So I just started learning Java, its literally like my 1st day and I wanted to try to make a coinflip game. I already know a decent amount of Javascript and so i was trying to apply that knowledge to java. So everything has been working so far except one thing: Prompting a user for a choice. So read online that i have to import a scanner so i did that as you can see from my code. I also tried some code where you can have the user import a string but you can see a bit later in my program i change the variable userChoice into a number. So basically i just need help with this. If there is some way to have a variable type that can store both numbers or strings that would be best. But im tottaly open to other ways of doing this! Thanks in advanced! Here is the code:
package test;
import java.util.Scanner;
public class testclass {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("hi");
int bob;
bob = (int) Math.floor(Math.random()*2);
System.out.println(bob);
System.out.println("Enter heads or tails?");
System.out.println("You entered "+ userChoice);
if (bob == 0) {
System.out.println("Computer flipped heads");
}
else {
System.out.println("Computer flipped tails");
}
if(userChoice == "Heads") {
userChoice = 0;
}
else {
userChoice = 1;
}
if (userChoice == bob) {
System.out.println("You win!");
}
else {
System.out.println("Sorry you lost!")
}
}
}
Use a scanner, as you said:
Scanner in = new Scanner(System.in);
Then, prompt the user to enter something in:
String userChoice = in.nextLine();
Also, when you compared strings:
if(userChoice == "Heads") {...
that's bad to do for none-primitive objects. It's best to only use the == to compare values that are ints or enums. If you compare a String like this, it won't work, because it's checking if the objects are the same. Instead, compare like this:
if(userChoice.equals("Heads")) {...
Also, to convert to an int (NOTE: You can't convert one type of object to another that aren't related in any way! You'll have to create a new object if you're wanting to do that), do this:
int myInt = Integer.parseInt(myString); // NOTE: Can throw NumberFormatException if non-number character is found.
So your program should look somewhat like:
package test;
import java.util.Scanner;
public class testclass {
public static void main(String[] args) {
//System.out.println("hi");
Scanner in = new Scanner(System.in);
int bob;
int userChoice;
String input;
bob = (int) Math.floor(Math.random()*2);
System.out.println(bob);
System.out.println("Enter heads or tails?");
input = in.nextLine(); // waits for user to press enter.
System.out.println("You entered "+ input);
if (bob == 0) {
System.out.println("Computer flipped heads");
}
else {
System.out.println("Computer flipped tails");
}
if(input.equals("Heads")) {
userChoice = 0;
}
else {
userChoice = 1;
}
if (userChoice == bob) {
System.out.println("You win!");
}
else {
System.out.println("Sorry you lost!");
}
in.close(); // IMPORTANT to prevent memory leaks
}
}
You've already imported the Scanner class so you can now create a variable of the type Scanner for taking inputs.
Scanner in = new Scanner();
userChoice = in.nextLine();
nextLine() can be used to input a character or a string from the user.
To convert the string into a integer, You can assign the integer value to the string in the following way.
if(userChoice == "Heads") {
userChoice = "" + 0;
}
else {
userChoice = "" + 1;
}
"String" datatype in Java can hold both numbers and strings (as you asked). You can get user input using Scanner utility as below:
Scanner input = new Scanner();
userChoice = input.nextLine(); // if it is a string
//userChoice = input.nextInt(); // if it's integer choice
If your string is an integer then you can also parse it to get its integer value. For parsing:
int value = Integer.parseInt(userChoice);
Also for comparing String values you should use "equals" function rather than "==".
if(userChoice.equals("Heads")){...} //rather than if(userChoice == "Heads"){...}
Having imported java.util.Scanner, to get input from the user as a String, create a Scanner object that parameterizes System.in and assign userChoice the value of nextLine() invoked by the Scanner object:
Scanner input = new Scanner(System.in);
String userChoice = input.nextLine();
A few things about your code. The relational operator, ==, is used for comparing primitive data - not objects. Use string1.equals(string2) to see if two strings are equal.
Also, bob = (int) Math.floor(Math.random()*2); is really bob = (int)(Math.random() * 2);
because casting a double as an integer truncates the double to the highest integer less than or equal to it.
It might help you to get the ideas.
public static void main(String[] args) {
Random rd = new Random();
//Enter 1 0R 0
int bob = rd.nextInt(2);
String userChoice;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number");
userChoice = sc.nextLine();
System.out.println("You entered " + userChoice + " and bob is " + bob);
int uc = Integer.parseInt(userChoice);
if (uc == bob) {
System.out.println("Hehe");
} else {
System.out.println("Sorry");
}
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
This relates to the method userInput() and its if statements. The output for userInput() is 0 no matter what, why? I know the initial value of calculate = 0; but i want to change it so that each time the user enters "Paper" for example the value of calculate = 1; IVE TRIED EVERYTHING! now im stuck wondering whats wrong with my if statements. Please help. (sorry if i'm a noob)
import java.util.Scanner;
class RPS{
private static String[] userOption = new String[]{"Rock", "Paper","Scissors"};
public static void main(String[] args){
System.out.println("Enter: Rock, Paper Or Scissors");
System.out.println(userInput());
}
public static int userInput(){
int calculate = 99;
Scanner input = new Scanner(System.in);
String userChoice = input.nextLine();
if(userChoice == userOption[0]){
calculate = 0;
} else if(userChoice == userOption[1]){
calculate = 1;
} else if(userChoice == userOption[2]){
calculate = 2;
}
return calculate;
}
}
You have to use the equals Method if you are working with strings.
e.g.:
if(userChoice.equals(userOption[0]))
Because if you use == it checks whether the references to the objects are equal.
This question already has answers here:
Java being able to choose wether to add or subract
(3 answers)
Closed 9 years ago.
the idea is that if for example they choose * if will say wrong operator please try again but at the moment that is just looping if I choose the wrong operator and also if I choose the right operator the program needs to end , I cant seem to figure it out
my code is as follows
import java.util.Scanner;
public class Uppgift5 {
public static void main (String[] args){
int tal1, tal2;
int sum = 0;
int sub=0;
String operator;
Scanner input = new Scanner (System.in);
Scanner input2 = new Scanner (System.in);
System.out.println("write in first digit");
tal1 = input.nextInt();
System.out.println("Write in 2nd digit ");
tal2 = input.nextInt();
System.out.println("Enter + to add and - subtract ");
operator = input2.nextLine();
while (operator.equals("-") || operator.equals("+")|| operator.equals("*") || operator.equals(("/")) ){
if (operator.equals("+")){
sum = tal1+tal2;
System.out.println("the sum is " + sum);
}
else if (operator.equals("-")){
sub = tal1-tal2;
System.out.println("the subtracted value is " + sub);
}
if (operator.equals("*") || operator.equals("/")){
System.out.println("You have put in the wrong operator, your options are + or -");
}
}
}
}
Your problem is here:
operator = input2.nextLine();
while (operator.equals("-") || operator.equals("+")|| operator.equals("*") || operator.equals(("/")) )
Assume operator is +. The value of operator does not change within the while loop, so operator will always be +, and you have an infinite loop.
Your operator will never be different. For that reason, your loops never end. You should use if instead of while
Instead of using a while loop, use a do loop that starts before you read operator from the input and only loops back if operator is not + or -. Ideally the while at the end of the do loop should come before you attempt the calculation.
Well, of course your code never ends... because you have no stopping condition. Also, your looping condition is incorrect. As long as the operator is one of those values, the loop will run. Also, you never ask for an input inside the loop. The code below should work:
import java.util.Scanner;
public class tt {
public static void main (String[] args){
int tal1, tal2;
int sum = 0;
int sub=0;
String operator = "";
Scanner input = new Scanner (System.in);
Scanner input2 = new Scanner (System.in);
System.out.println("write in first digit");
tal1 = input.nextInt();
System.out.println("Write in 2nd digit ");
tal2 = input.nextInt();
System.out.println("Enter + to add and - subtract ");
while (true){
operator = input2.nextLine();
if (operator.equals("+")){
sum = tal1+tal2;
System.out.println("the sum is " + sum);
}
else if (operator.equals("-")){
sub = tal1-tal2;
System.out.println("the subtracted value is " + sub);
}
if (operator.equals("*") || operator.equals("/")){
System.out.println("You have put in the wrong operator, your options are + or -");
break;
}
}
}
}