Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm trying to create a program in which the user thinks of a number between 1 and 10, and the computer repeatedly tries to guess it by guessing random numbers. (It's ok to guess the same number more than once) At the end of the game, the program reports how many guesses it made. For example:
I have written the following code:
import java.util.*;
public class Pick {
public static void main(String[] args){
System.out.println("This program has you, the user, choose a number");
System.out.println("between 1 and 10. Then, I, the computer, will try");
System.out.println("my best to guess it.");
Scanner console = new Scanner(System.in);
Random r = new Random();
int result = -1;
int count = 0;
for (i = 1; i <= number; i++){
while(result != number){
result = r.nextInt(10) + 1;
System.out.println("Is it " + r + "? (y/n)");
String yn = console.next();
if(String yn = "y"){
System.out.println("I got your number of " + result + " in " + i + " guesses.");
} else if (String yn = "n") {
count++;
} else {
System.out.println("I got your number of " + result + " in " + i + " guesses.");
}
}
System.out.println();
}
}
I'm confused as to why my program doesn't work? It won't compile and has 7 errors. I think I went wrong in the if/else statements. Should I have used a while loop?
Thanks.
compilation errors by text:
Pick.java:20: error: ')' expected
if(String yn = "y"){
^
Pick.java:20: error: ';' expected
if(String yn = "y"){
^
Pick.java:22: error: ')' expected
} else if (String yn = "n") {
^
Pick.java:22: error: ';' expected
} else if (String yn = "n") {
^
Pick.java:22: error: 'else' without 'if'
} else if (String yn = "n") {
^
Pick.java:25: error: 'else' without 'if'
} else {
^
Pick.java:31: error: reached end of file while parsing
}
^
7 errors
You are trying to use the variable number at for (i = 1; i <= number; i++){ but it doesn't exist. You need to initialize number.
For one thing,
if(String yn = "y") {
}
is not what you think it is in Java. String yn = "y" is an assignment statement, not a comparison.
To compare strings in Java you want to use String's equals() method.
There's are more syntax issues and obvious compiler errors. I suggest you try out one of the many tutorials online for beginning Java.
String yn = console.next();
if(String yn = "y"){
You are declaring yn twice. That's not allowed. Just use yn, no need to speficy it's a String again, you already did.
You're using assignement operator = instead of comparison operator ==. In any case, Strings in Java are not compared using == but using equals method if(yn.equals("y"))
for (i = 1; i <= number; i++)
I don't see the error message for this, but still number is not declared anywhere.
Related
I am trying to make a letter gusser in java but my while loop won't work. The error I am getting is
error: bad operand types for binary operator '!='
while (input != ranLetter){
^
first type: String
second type: char
1 error.
I tried to converting ranLetter to a char but then the loop never stops.
Here is my code:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int ranNum = (int)(Math.random()*26 + 97);
char ranLetter = (char)ranNum;
//This is just for testing
System.out.println(ranLetter);
String input = in.nextLine();
if (input == String.valueOf(ranLetter)){
System.out.println("FIRST TRY BTW!! the letter was " + ranLetter + ".");
}
else{
int counter = 0;
while (input != ranLetter){
System.out.println("Nope :( try again.");
counter += 1;
input = in.nextLine();
}
System.out.println("Nice you got it. The letter was " + ranLetter + ". It took you " + String.valueOf(counter) + " guesses.");
}
}
}
You can't compare String and char,
moreover, you should use .equals() method to compare input and String.valueOf(ranLetter) because
"A" == String.valueOf('A')
is always false
You are trying to compare a String against a char:
while (input != ranLetter)
change to this instead:
while (!input.equals(String.valueOf(ranLetter)))
as well as input == String.valueOf(ranLetter) to input.equals(String.valueOf(ranLetter)
This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 5 years ago.
Building a survey application, and I am running into a roadblock with this problem. I am not understanding where my issue is exactly but when I am trying to create a two option menu, it is not allowing me to compile or run it.
errors:
Compiling 2 source files to C:\Users\martin.shaba\Documents\NetBeansProjects\Survey\build\classes
C:\Users\martin.shaba\Documents\NetBeansProjects\Survey\src\survey\Survey.java:71: error: cannot find symbol
System.out.print("Enter text for question " + (i+1) + ": ");
symbol: variable i
location: class Survey
C:\Users\martin.shaba\Documents\NetBeansProjects\Survey\src\survey\Survey.java:75: error: cannot find symbol
questions[i] = new IntegerQuestion(input.nextLine(),maxResponses);
symbol: variable i
location: class Survey
2 errors
C:\Users\martin.shaba\Documents\NetBeansProjects\Survey\nbproject\build-impl.xml:930: The following error occurred while executing this line:
C:\Users\martin.shaba\Documents\NetBeansProjects\Survey\nbproject\build-impl.xml:270: Compile failed; see the compiler error output for details.
BUILD FAILED (total time: 1 second)
Here's how I want it to be...
Choose from the following options:
S - Create a question in a string
N - Create a question in an integer
my current code:
package survey;
import java.util.Scanner;
import java.io.Serializable;
public class Survey implements Serializable
{
private String surveyName;
private Question[] questions;
private int numQuestions;
private int maxResponses;
private boolean initialized;
public Survey(String n)
{
surveyName = n;
initialized = false;
}
//initialize() sets up the numQuestions, MaxResponses, and questions for the survey
public char Questions()
{
Scanner input = new Scanner(System.in);
System.out.println("Initializing survey \"" + surveyName + "\"\n");
//add a method for password validation!?!?!? yes!!! see the bank accounts lab
System.out.print("Enter max number of responses: ");
maxResponses = input.nextInt();
System.out.print("Enter number of questions: ");
numQuestions = input.nextInt();
input.nextLine(); //have to do this to "eat" the new line character or the next input won't work correctly
System.out.println();
questions = new Question[numQuestions];
for(int i = 0; i < numQuestions;i++)
{
char choice;
//output menu options
System.out.println();
System.out.println(" S - Create String Question");
System.out.println(" N - Create Integer Question");
//loop until a valid input is entered
System.out.print("Enter choice: ");
choice = input.next().charAt(0);
//if choice is one of the options, return it. Otherwise keep looping
if(choice == 'S' || choice == 'N' )
return choice;
else
{
System.out.println("Invalid choice. Ensure a capital letter. Please re-enter.");
choice = '?';
}
(choice == '?');
return choice; //will never get here, but required to have a return statement to compile
}
System.out.print("Enter text for question " + (i+1) + ": ");
//you will also need to ask what KIND of question - right now, defaults to integer question
questions[i] = new IntegerQuestion(input.nextLine(),maxResponses);
initialized = true;
}
/*
run() gives the survey to a new survey taker, basically asks all the questions in the survey
*/
public void startSurvey()
{
if(initialized)
{
System.out.println("Welcome to the survey \"" + surveyName + "\"\n");
for(int i = 0;i < numQuestions; i ++)
{
questions[i].askQuestion();
}
System.out.println("Thank you for participating!");
}
else
{
System.out.println("Survey has not yet been setup. Please initialize first.");
}
}
/*
displayResults() displays the raw data for the survey
*/
public void Results()
{
System.out.println("Displaying data results for \"" + surveyName + "\"\n");
for(int i = 0;i < numQuestions; i ++)
{
questions[i].displayResults();
System.out.println();
}
}
/*
displayReportSummary() should run tests on your data
Examples could be: the most common response (median), the average response (mean), or display a graph of the results?
The choices are endless!
*/
public void reportSummary()
{
}
}
You're using i outside the loop. Because you declared i in the for loop, the scope of i is the loop only. It ceases to exist as soon as the loop ends.
The error messages from the compiler tell you which line of code the error is on, and exactly what the error is. It's worth learning to read these.
I'm trying to run this program as a loop when the user inputs a "Y" value in. I want the input to ignore the case, so that the user can enter "y" or "n" also. Would I use the equalsIgnoreCase() method? And if so, would I want to change my char to a boolean? I'm still very new to java about a month in, so any help would be appreciated. I've been playing around with this for awhile now and I can't figure it out without at least one error.The fact that I got it to loop at all is a miracle at this point :)
char Again = 'Y';
while(Again == 'Y')
{
long product = 1, count = 0;
System.out.println("This program will generate a table of powers of a number.");
System.out.println("You just have to tell me what number: \n\n");
System.out.print("Enter an integer please: ");
int MyNum = Fred.nextInt();
while(count<5)
{ product = product * MyNum;
System.out.print(product + ",");
count = count + 1;
}
System.out.println("\nBye for now.....");
System.out.print("\n\n\n Try another number (y/n)?");
String Word = Fred.next();
Again = Word.charAt(0);
}
char is primitive data type, it doesn't have member functions. So you need to check both the lower case and upper case if you stick with char:
while(Again == 'Y' || Again == 'y')
Or, you can declare Again as String: Again = Word.toUpperCase(); then use while("Y".equals(Again))
Or, just, Again = Word; then while("Y".equalsIgnoreCase(Again))
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I have this program set up and i need help with 2 errors that i am getting
import java.util.Scanner;
public class EvenOdd {
public static void main(String[]args) {
Scanner keyboard = new Scanner (System.in);
System.out.print("---EvenOdd--- /n");
System.out.printf("Enter a whole number: ");
c = in.nextInt();
}
public static EvenOdd (int num) {
int c = num;
if (int.class)
(c/2)*2 = c;
System.out.println("is even.");
else (c)
System.out.println("is odd");
return EvenOdd;
}
}
C:\Users\Desktop\EvenOdd.java:28: error: not a statement
else (c)
C:\Users\Desktop\EvenOdd.java:28: error: 'else' without 'if'
else (c)
2 errors
Your else doesn't make sense. First of all, you are not using braces, but also your boolean logic does not make sense. Just adding braces will not make your code compile.
I think this rewrite is the closest to what you have
public static boolean EvenOdd (int num) {
// Here your calculation is done
boolean isEven = (c/2)*2 == c;
if (isEven) {
System.out.println("is even.");
} else if (!isEven) {
// Using 'else if' for a boolean parameter does not make much sense
// but i'll leave it here to explain the syntax
System.out.println("is odd");
}
return isEven;
}
However, the most common way to check for odd or even is using the modulus operator. And if i make the entire code a bit more java-ish, you'd end up with (for example method-naming)
/**
* Check if the given number is even.
* #param num the number to check
* #return whether num is an even number
*/
public static boolean isEven (int num) {
if ((x % 2) == 0) {
System.out.println("is even.");
return true;
} else {
System.out.println("is odd");
return false;
}
}
Here is a solution
public static void main(String[]args)
{
Scanner keyboard = new Scanner(System.in);
try{
System.out.println("---EvenOdd---");
System.out.print("Enter a whole number: ");
int c = keyboard.nextInt();
evenOdd(c);
}finally{
keyboard.close();
}
}
public static void evenOdd(int num)
{
int c = num;
if ((c/2)*2 == c){
System.out.println("is even.");
}else {
System.out.println("is odd");
}
}
Output:
for the input value 5
---EvenOdd---
Enter a whole number: 5
is odd
for the input value 4
---EvenOdd---
Enter a whole number: 4
is even.
Continued Reading
There are several problems with the original code and I will attempt to explain them in line order.
Original code for reference:
public class EvenOdd {
public static void main(String[]args) {
Scanner keyboard = new Scanner (System.in);
System.out.print("---EvenOdd--- /n");
System.out.printf("Enter a whole number: ");
c = in.nextInt();
}
public static EvenOdd (int num) {
int c = num;
if (int.class)
(c/2)*2 = c;
System.out.println("is even.");
else (c)
System.out.println("is odd");
return EvenOdd;
}
}
First we have this line
System.out.print("---EvenOdd--- /n");
use of the .print() method here, while not illegal is unnecessary because java provides us with .println() which automatically creates a new line so we don't have to. (i.e. with "/n")
System.out.printf("Enter a whole number: ");
Next you use the .printf() method, this prints a formatted output and accepts arguments as a parameter. You aren't using any of the exclusive features of this method so we can achieve the same functionality with .print().
c = in.nextInt();
the variable in is not defined in this scope, I presume that you meant to use keyboard.nextInt().
public static EvenOdd (int num) {
when a method has no return type and the same name as the class it resides in (case sensitive) it is a constructor. Constructors do not require a return statement and are invoked with the syntax new ObjectConstructor() usually to assign a value to a variable of the same type as the constructor.
if (int.class)
(c/2)*2 = c;
System.out.println("is even.");
else (c)
System.out.println("is odd");
This if-else block is clearly not even java syntax.
first there is no need to cast your result to an int and the semicolon at the end of your conditional doesn't belong.
removing these errors brings us to:
if (c/2)*2 = c
System.out.println("is even.");
else (c)
System.out.println("is odd");
now we need to wrap our conditional in parentheses '( and )' and rather than use the assignment operator '=' we should use the comparison operator '==' which returns a boolean. Also, the else clause does not require a condition, if you would like to use a condition look into elseif.
these changes get us to this step.
if ((c/2)*2 == c)
System.out.println("is even.");
else
System.out.println("is odd");
Now we add proper brackets and we are good to go.
if ((c/2)*2 == c){
System.out.println("is even.");
}else{
System.out.println("is odd");
}
I'm relatively new to Java and I'm trying to write a program for my computer programming class that will accept a string from the user (the string must be something like 1 + 2 - 1) and then take the string, use a delimiter to get rid of the +/- signs, and then perform the addition and subtraction and return the sum of the string input. To do this, my program has to run through a while loop and each time an integer is found it must perform the appropriate function based on whether a + or - sign preceded the number. I'm trying to use .findInLine to have the program determine whether the character is a + or - and then based on this add or subtract the number that follows, but it doesn't seem to work while also using a delimiter and I'm stuck as to what to do. Here's my code:
import java.util.*;
import java.io.*;
public class Lesson17p1_ThuotteEmily
{
public static void main(String args[])
{
Scanner kb=new Scanner(System.in);
System.out.println("Enter something like 8 + 33 + 1,257 + 137");
String s=kb.nextLine();
Scanner sc=new Scanner(s);
char c=sc.findInLine("\\+").charAt(0);
sc.useDelimiter("\\s*\\+\\s*");
double sum=0;
while(sc.hasNextInt());
{
if(c=='+')
{
sum=sum+sc.nextInt();
System.out.println(sum);
}
}
System.out.println("Sum is: "+sum);
}
}
I had code for - signs in the program previously but deleted them temporarily because I want to figure out how to make the program run for addition problems and then I'm going to add in the subtraction programming later, using the same thing that worked for addition.
My code compiles and runs fine, but when it gets to the part where it should be adding and then returning the sum of the problem, it stops. It doesn't return an error or anything, it just freezes. I'm not really sure why this is happening. I need the delimiter for the loop and addition to work, and when I tried taking that out it returned an error. I could remove the find in line but then I'll need a different way for the program to determine whether to add or subtract and I'm struggling to think of anything. I've also tried rearranging my code so it will find the + or - sign first, then use a delimiter to get rid of the symbol and proceed with the addition or subtraction, but again the program froze.
Any help you can give is much appreciated!
Remade the code with comments:
import java.util.Scanner;
import java.util.LinkedList;
public class AddSubstract {
public static void main(String[] args) {
Scanner userInputScanner = new Scanner(System.in);
System.out.print("Type in an expression using + and - operators.\n>> ");
String userInput = userInputScanner.nextLine();
// our example input: " 35 - 245 + 34982 "
userInput = userInput.trim();
// input is now "35 - 245 + 34982"
if(userInput.charAt(0) != '-') userInput = "+" + userInput;
// we need to change the input to a set of operator-number pairs
// input is now "+35 - 245 + 34982"
int result = 0;
// result
byte sign = 0;
// sign; 1 -> positive number, -1 -> negative number, 0 -> not yet checked
int numberToPush = 0;
for(char c : userInput.toCharArray()) {
if(c == '+' || c == '-') {
if(sign == 0) sign = (c == '+')?1:-1;
else {
result += sign*numberToPush;
sign = (c == '+')?1:-1;
numberToPush = 0;
}
} else if(c >= '0' && c <= '9') {
numberToPush = ((int) c-'0') + 10*numberToPush;
}
}
result += sign*numberToPush;
System.out.println("The result is: "+result);
}