I am learning JAVA and trying to write my first loop. The loop should prompt the user to guess a defined name.
The code is not performing right. I have tried to search for help on different JAVA tuturials both not found any examples where you guess a name/string but a lot where you should guess a number.
This is my code:
/**
*
* #author mso_
*/
import java.util.Scanner;
public class GuessName {
/**
* #param args the command line arguments
*/
public static final int C_Max_Trials = 10;
public static void main(String[] args) {
//Define correct name
String name = "Morten";
String guessName;
//Create a scanner
Scanner guess = new Scanner(System.in);
//Recieve a guess
do {
System.out.println("Please guess my name. Enter your guess here: ");
String guessName = guess.next(); <-- ERROR
//Create loop
} while (guessName != name); <-- ERROR
System.out.println("Sorry, wrong guess, please enter another guess: ");
if (guessName = name); <-- ERROR
System.out.println("Right on! ");
}
}
What have I done wrong?
String comparison
You can't compare Strings like this. This will only compare the references. You must use the equals() method :
while (! guessName.equals(name));
A little explanation : http://www.zparacha.com/java-string-comparison/
Variable redeclaration
There is another error in your code, you try to redeclare guessName inside the loop. You must declare guessName only once outside of the loop (ie before the do {).
General mistakes
Thirdly, there's a some other errors in your code. I think all of them were pointed out in the others answer, but I'll do a quick list :
if (guessName = name); This is a useless statement as is, you must open a block : if(condition) { statement; }
Same line, your doing an assignment, not a comparison, and like said, with String you must use .equals()
The System.out.println() won't be executed when you think. Re-read the doc about do { } while() loop until you really understand them.
My advise : read carefully the error message of your compiler and read some doc before writing code.
What errors?
Use .equals when comparing strings
You are using the assignment operator and not the equivalence operator at
if (guessName = name)
you need to do
if(guessName.equals(name)) instead.
You're comparing references (well, with guessName = name, you're actually assigning a value to guessName). Use String.equals() instead of == and !=.
you are comparing two objects. Not two string values.
use equals
That won't compile for a start - you declare String guessName on the third line of the main method, and then declare the same variable again within the do loop. You should simply use the name of the variable to assign to it:
guessName = guess.next();
Because of this error, presumably your IDE's compiler doesn't see the variable at all, so the subsequent lines that refer to guessName are also flagged as errors. Fixing this first line should clear those up, unless there's another problem lying there that I've missed.
Among other things there is a wrong semicolon after the if:
if (name.equals(guessName)) //removed the semicolon and use .equals
System.out.println("Right on! ");
and it's an assignment instead of a comparison as other answers state by now.
Try this
public class GuessName {
/**
* #param args the command line arguments
*/
public static final int C_Max_Trials = 10;
public static void main(String[] args) {
//Define correct name
String name = "Morten";
String guessName = null;
//Create a scanner
Scanner guess = new Scanner(System.in);
//Recieve a guess
do {
System.out.println("Please guess my name. Enter your guess here: ");
guessName = guess.nextLine(); <-- ERROR
if(!guessName.equals(name))
{
System.out.println("Sorry, wrong guess, please enter another guess: ");
}
//Create loop
} while (!guessName.equals(name)); <-- ERROR
if (guessName.equals(name)) <-- ERROR
System.out.println("Right on! ");
}
}
The line String guessName = guess.next(); needs to be changed to:
guessName = guess.next();
Because "guessName" is already defined earlier.
Additionally, when you compare strings you need to use the method equals and not the operator ==. So } while (guessName != name); should be:
} while (!guessName.equals(name));
And if (guessName = name); should be changed to:
if (guessName.equals(name))
Here is what the javac compiler says:
GuessName.java:26: guessName is already defined in main(java.lang.String[])
String guessName = guess.next(); //<-- ERROR
^
GuessName.java:32: incompatible types
found : java.lang.String
required: boolean
if (guessName = name);// <-- ERROR
^
2 errors
For the first one, you should not declare another local variable: drop the String. For the second, use .equals to compare String objects, as the doc says.
You will obtain something like that:
...
//Recieve a guess
do {
System.out.println("Please guess my name. Enter your guess here: ");
guessName = guess.next(); //<-- FIXED
//Create loop
} while (!guessName.equals(name)) //<-- FIXED
if (guessName.equals(name))// <-- FIXED
System.out.println("Right on! ");
}
...
which works correctly.
The strings must be compared using the equals method.
Related
am trying to refer back to line 8 but don't know how, sorry am new to Java.
I've tried many approaches but still hitting a wall, pls what should I do.
package Interview;
import java.util.Scanner;
public class Interview {
public static void main(String[] args) {
System.out.println("hello,please what is your name:");
System in = scanner(System.in);
String Input=in.nextLine();
System.out.println("well then welcome to startechz "+Input);
System.out.println("Are you a male or female:");
String Input=in.nextLine();
if (Input=male)
//recall outprint from line 8
System.out.println("once again, welcome mr"+Input of Line8);
else {
System.out.println("once again,welcome mrs"+Input of Line8);
}
}
there many syntax error on your code it would be better to use ide
change this
System in = scanner(System.in);
to
Scanner in = new Scanner(System.in);
you can not redefine same variable again you have to statement
that looks like this
String Input=in.nextLine();
to solve this either use this
String newInput=in.nextLine();
or just assign new value to the same variable (of course of course if you do not want to use the old one again) like that
Input=in.nextLine();
in java to compare value you use double = sign like
Input==male
single = are used to assign value like int value = 5;
you can use == with primitive type only it will work but for reference type it will not work as in your case you use String with is reference type
why it did not work with reference type cause it will compare the reference address (the address for the object in memory (to be accurate it not the physical address but think of it like that))
so use the equal method
like
if (Input.equals("male")) // you forget also to make male as string you forget the double quotations
Change
if (Input=male)
to
if(Input.equalsIgnoreCase("male")) // allows case independent compare
Use equals or equalsIgnoreCase to compare strings.
So recently I've switched over from python to java and was trying to recreate some of the projects that I made on python in java. The first thing that came to mind was a quiz.
Basically, to create a quiz, I define an answer variable to the answer then use the scanner method in java to detect the user's input. After that, I use an if statement to see if the input equals the answer.
ex.
class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String answer = "dog";
System.out.println("What is a common furry animal");
String input = scan.nextLine( );
if (input.equals(answer))
{
System.out.println("Correct");
}
else
{
System.out.println("Inncorect");
}
}
}
Now that all works but the user doesn't know the exact casing of the answer variable which means if the variable was "dog" and he input "Dog" it would be incorrect. So if it was possible to create an "or" condition to an if statement it would be awesome if someone let me know.
-Thanks
To or any condition in Java, use the conventional || to separate conditions. In your case it would be something like:
if (input.equals(answer) || input.equalsIgnoreCase(answer))
Although you probably just need the Java method equalsIgnoreCase as the lone condition in the first place.
Trying to test my java "skills" and make a text based game--except i can't get the user input. i already importd the scanner class, and it works well w/ integers so idk what the problem is quite frankly. whenever i try to compile it, the lines containing "String name = scanner.next();" show up with a 'Scanner cannot be resolved' error.
import java.util.Scanner;
public class CH1 {
public static void main (String args[]) {
Scanner s= new Scanner( System.in);
int answer;
System.out.println ("You're in grave danger, but first, I must know your name. Will you tell me? ");
answer = s.nextInt();
if (answer == 1) {
System.out.println ("I respect your decision, but I'll need to know your name
if you turn up dead, unless you want to have a one man funeral.");
System.out.println ("What's your name?");
String name = scanner.next();
}
else if (answer == 2) {
System.out.println("Great, now what's your name?");
String name = scanner.next();
}
else {
System.out.println(" Huh? I didn't really get that. (1 for no, 2 for yes.)");
}
}
}
You named that scanner s first!
You can't just use a different name later on!
So simply change the scanner variable name to "scanner" and keep using that name.
Beyond that: Single character variable names are something you almost never do (except for index values in for loops). The point is: variable names should say something about the thing they denote. "s" says nothing!
I need to check the array to see if the user input is already present, and display a message as to whether it is or isn't there. The first part is working, but I tried to create a method for the word check, and I'm not sure if I'm on the right path or not, cheers.
import java.util.Scanner;
public class InputLoop {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String array[] = new String[10];
int num = array.length, i = 0;
System.out.println("Enter a word");
for (i = 0; i < num; i++) {
while (scan.hasNextInt()) // while non-integers are present...
{
scan.next(); // ...read and discard input, then prompt again
System.out.println("Bad input. Enter a word");
}
array[i] = scan.next();
WordCheck();
}
}
public void WordCheck(String[] i) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter another word");
if (scan.next().equals(array[i])) {
System.out.println("The word has been found");
} else {
System.out.println("The word has not been found");
}
}
}
Right. You've clearly gone down a bad thought process, so let's just clear the slate and have a re-think.
Step one: You want to take some user input
Step two: Compare it with all previous user inputs to see if it's present.
If it is present, return a message indicating that value has been inputted.
otherwise ignore the input and continue execution
Repeat step one.
The solution
So, let's review what you've got, and how you need to change it.
public static void main(String[] args)
If I were you, I would avoid calling methods directly from here. If you do, every method will need to be static, which is a pointless adjustment in scope for the functionality of your class. Create a new instance of your class, inside the main method, and move this code to the class' constructor. This will remove the need to make every single method static.
Scanner scan = new Scanner(System.in);
String array[] = new String[10];
Okay, so you've created a scanner object that takes input from the System.in stream. That's a reasonable thing to do when taking input from the keyboard. You've also created an array to contain each item. If you only want the user to be able to type in 10 values, then this is fine. Personally, I would use an ArrayList, because it means you can take in as many user inputs as the user desires.
Secondly, you want a function to compare the input, with all other inputs. What you have at the moment clearly isn't working, so let's have another go at it.
You will need some input, userInput, and a collection to compare it against, allInputs.
allInputs needs to be accessible from any point in the program, so it's probably wise to make it into a field, rather than a local variable.
Then, because you're comparing userInput against all values, you're going to need a foreach loop:
for(String s : allInputs)
{
if(s.equals(userInput))
{
// Output message code.
}
}
Now the trick is fitting this inside a loop that works with this program. That is up to you.
One simple solution is to use a Set:
Set<String> words = new HashSet<String>();
Add words with the add() method and check if a word is already added with contains(word) method.
EDIT
If you must use Arrays you can keep the array sorted and do a binary search:
Arrays.sort(words);
boolean isAlreadyAdded = Arrays.binarySearch(words, newWord) >= 0;
You're going to have to loop through the entire array and check if scan.next() equals any of them - if so return true - as such:
String toCheck = scan.next();
for (String string : i) { //For each String (string) in i
if (toCheck.equals(i)) {
System.out.println("The word has been found");
return;
}
}
System.out.println("The word has not been found");
This supposes you call WordCheck(), passing the array to it - this method also has to be static for you to call it from the main() method.
You can use the arraylist.contains("name") method to check if there is a duplicate user entry.
Doing some homework here (second assignment, still extremely green...). The object is to read in number x and y and provide the number in the hundreds position.
For this, I need to use int's I'd assume, as a requirement is to utilize value-returning methods.
I'm just starting to code this, however I'm hitting compile errors already:
Exception in thread "main" java.lang.Error: Unresolved compilation
problems:
Illegal modifier for parameter anum; only final is permitted
Illegal modifier for parameter bnum; only final is permitted
Type mismatch: cannot convert from String to int at Hundreds.main(Hundreds.java:6)
Where am I going wrong?
Here is the code so far:
import java.util.Scanner;
public class Hundreds {
public static void main (String [] args) {
Scanner input = new Scanner(System.in);
private int anum,bnum;
System.out.println("Hello, for this assignment we are going to require the user to enter two distinct numbers of their choosing");
System.out.println("Please ensure the numbers are between 100 and 9999");
System.out.println("\n");
System.out.println("Please enter your first Number: ");
anum = input.nextLine();
Since those variables are local, you can't set visibility scopes to them like private, public, protected.
Move them out of the main function if you intend their scope to be larger.
anum = Integer.valueOf(input.nextLine());
You can also test to see if the next element is an int, and then give feedback to the user if it's not:
if(input.hasNextInt()) {
anum = input.nextInt();
}
Make anum string instead of int. nextLine return a string. don't use private either while defining your string within main.
Try this instead:
anum = input.nextInt();
This will still error out if you input a non-integer (try it to see the fun stack trace), but will get you past where you're at currently.
(i) Remove invalid modifiers.
(ii)Convert string to integer. So make use of anum=input.nextInt() instead of anum=input.nextLine()