I am getting 3 illegal start of expression errors? [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Please help me with this. I feel like this is really simple and I am probably going to feel really stupid when its all said and done. Thank You.
I have tried multiple things but none seem to work.
Yes, I am more familiar with Visual Basic than Java, that is why I am having this problem.
import java.util.Scanner;
public class YuGiOhLifePointCounter {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
double choice_1;
System.out.print("\nEnter the starting life points for player-1: ");
choice_1 = sc.nextDouble();
double storage_1;
storage_1 = choice_1;
double choice_2;
System.out.print("\nEnter the starting life points for player-2: ");
choice_2 = sc.nextDouble();
double storage_2;
storage_2 = choice_2;
double lp;
System.out.print("\nEnter a 6 to change the life-points of either player: ");
lp = sc.nextDouble();
double display_1 = choice_1;
double display_2 = choice_2;
while (lp == 6) {
/* Starting here*/
if (display_1 <== 0) {
System.out.println("Player-2 has won the game.");
System.exit(0);
}
if (display_2 <== 0) {
System.out.println("Player-1 has won the game.");
System.exit(0);
}
if (display_1 <> 0 && display_2 <> 0) {
/* these 3 if statements above are giving me illegal import errors, I can't figure out why. Thank You.*/
double choose_1_2;
System.out.print("\nEnter a 1 to change player-1's life-points, or enter a 2 to change player-2's life-points: ");
choose_1_2 = sc.nextDouble();
if (choose_1_2 == 1) {
double ch_1;
System.out.print("\nEnter the number subtracted from or added to player-1's life-points: ");
ch_1 = sc.nextDouble();
double c_1;
System.out.print("\nEnter a 1 to subtract this number from player-1's life-points, or enter a 2 to add this number to player-1's life-points: ");
c_1 = sc.nextDouble();
if (c_1 == 1) {
display_1 = storage_1 - ch_1;
System.out.println("\nPlayer-1's life-points are currently " + display_1);
}
if (c_1 == 2) {
display_1 = storage_1 + ch_1;
System.out.println("\nPlayer-1's life-points are currently " + display_1);
}
}
if (choose_1_2 == 2) {
double ch_2;
System.out.print("\nEnter the number subtracted from or added to player-2's life-points: ");
ch_2 = sc.nextDouble();
double c_2;
System.out.print("\nEnter a 1 to subtract this number from player-2's life-points, or enter a 2 to add this number to player-1's life-points: ");
c_2 = sc.nextDouble();
if (c_2 == 1) {
display_2 = storage_1 - ch_2;
System.out.println("\nPlayer-2's life-points are currently " + display_2);
}
if (c_2 == 2) {
display_2 = storage_1 + ch_2;
System.out.println("\nPlayer-2's life-points are currently " + display_2);
}
}
}
}
}
}

if (display_1 <= = 0)
if (display_1 <> 0)
Not sure what you're trying to do exactly, but these aren't right.
If you want to check for display_1 less than 0, then you need:
if (display_1 < 0)
If you want to check for display_1 less than or equal to 0, then you need:
if (display_1 <= 0)
If you want to check for display_1 equal to 0, then you want:
if (display_1 == 0)
If you want to check for display_1 not equal to 0, then you want:
if (display_1 != 0)

Related

Java Program Quiz [closed]

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 13 hours ago.
Improve this question
I am trying to create a 5 questions quiz, after question 4 it automatically prints question 5 and not ask first, and then proceeds on printing the results. here is my code
import java.util.Scanner;
public class quiz {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String name, section;
int score, numQuestions = 5;
System.out.println("Welcome to the Basic Electronics Quiz!");
boolean repeat;
do {
// Get name and section
System.out.print("Enter your name: ");
name = scanner.nextLine().trim();
System.out.print("Enter your section: ");
section = scanner.nextLine().trim();
// Initialize score
score = 0;
// Question 1
System.out.println("\nQuestion 1: What is Ohm's Law?");
System.out.println("A. Voltage = Current x Resistance");
System.out.println("B. Current = Voltage x Resistance");
System.out.println("C. Resistance = Voltage / Current");
System.out.print("Answer: ");
String answer1 = scanner.nextLine().trim().toLowerCase();
if (answer1.equals("a")) {
System.out.println("Correct!");
score++;
}else {
System.out.println("Wrong. The correct answer is " + "A" + ".");
}
System.out.println();
// Question 2
System.out.println("\nQuestion 2: What is the unit of resistance?");
System.out.println("A. Ampere");
System.out.println("B. Volt");
System.out.println("C. Ohm");
System.out.print("Answer: ");
String answer2 = scanner.nextLine().trim().toLowerCase();
if (answer2.equals("c")) {
System.out.println("Correct!");
score++;
}else {
System.out.println("Wrong. The correct answer is " + "C" + ".");
}
System.out.println();
// Question 3
System.out.println("\nQuestion 3: An LED is a type of resistor. (True/False)");
System.out.print("Answer: ");
String answer3 = scanner.nextLine().trim().toLowerCase();
if (answer3.equals("true")) {
System.out.println("Correct!");
score++;
}else {
System.out.println("Wrong. The correct answer is " + "True" + ".");
}
System.out.println();
// Question 4
System.out.println("Question 4: What is the total resistance of two 10-ohm resistors in parallel?");
System.out.print("Your answer: ");
try {
double answer4 = scanner.nextDouble();
double expectedAnswer4 = 5.0;
if (Math.abs(answer4 - expectedAnswer4) < 0.0001) {
System.out.println("Correct!");
score++;
} else {
System.out.println("Wrong. The correct answer is " + expectedAnswer4 + ".");
}
System.out.println();
} catch (Exception e) {
// If there's an error parsing the input, don't add to score
}
// Question 5
System.out.println("\nQuestion 5: What is the term for a circuit that can generate an output signal with a fixed frequency?");
System.out.print("Your answer: ");
String answer5 = scanner.nextLine().trim().toLowerCase();
if (answer5.contains("Occilator") && answer5.contains("occilator")) {
score++;
}
else {
//System.out.println("Wrong. The correct answer is " + "Oscillator" + ".");
}
System.out.println();
// Display results
System.out.printf("\n%s, section %s, your score is %d/%d.\n", name, section, score, numQuestions);
// Ask to repeat
System.out.print("\nDo you want to take the quiz again? (yes/no): ");
String repeatStr = scanner.nextLine().trim().toLowerCase();
repeat = repeatStr.equals("yes") || repeatStr.equals("y");
} while (repeat);
System.out.println("\nThank you for taking the quiz!");
}
}
I tried copying only the question 5 to another file and it works but when i paste it again in the main file it will only proceeds on printing the results instead of asking for question 5
The problem is in using scanner.nextDouble();. You can read here more about why the problem occurs on this line.
You can solve your problem if you use Double.parseDouble(scanner.nextLine()); instead of scanner.nextDouble();.
Also, as Gilbert Le Blanc
has stated in the comments, you need to update the condition in your 5th question from answer5.contains("Occilator") && answer5.contains("occilator") to answer5.contains("Occilator") || answer5.contains("occilator"), otherwise you will never be able to answer the 5th question correctly. Here you also meant to write oscillator and not ocillator.
Here is an example output after implementing the solution:
Welcome to the Basic Electronics Quiz!
Enter your name: Aleksa
Enter your section: 1
Question 1: What is Ohm's Law?
A. Voltage = Current x Resistance
B. Current = Voltage x Resistance
C. Resistance = Voltage / Current
Answer: a
Correct!
Question 2: What is the unit of resistance?
A. Ampere
B. Volt
C. Ohm
Answer: c
Correct!
Question 3: An LED is a type of resistor. (True/False)
Answer: true
Correct!
Question 4: What is the total resistance of two 10-ohm resistors in parallel?
Your answer: 5
Correct!
Question 5: What is the term for a circuit that can generate an output signal with a fixed frequency?
Your answer: occilator
Aleksa, section 1, your score is 5/5.
Do you want to take the quiz again? (yes/no):

How to set integer range in Scanner? [closed]

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 1 year ago.
Improve this question
I am learning java and I want to create a command-line application that calculates exam percentages based on marks obtained. But the problem is I don't have the idea to set the range of marks obtained while the marks range is between 0 to 100.
Below is the code, I have tried: -
package com.company;
import java.util.*;
public class CbseCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter marks obtained of Physics");
float physics = sc.nextFloat();
System.out.println("Enter marks obtained of Chemistry");
float chemistry = sc.nextFloat();
System.out.println("Enter marks obtained of Math");
float math = sc.nextFloat();
System.out.println("Enter marks obtained of English");
float english = sc.nextFloat();
System.out.println("Enter marks obtained of Computer Science");
float computer = sc.nextFloat();
float total = 500;
float obtained = (physics + chemistry + math + english + computer);
float percentage = (obtained/total)*100;
System.out.println("The percentage obtained is: "+percentage);
sc.close();
}
}
It is not a good idea to try to get Scanner to do that1.
Instead, you should use Scanner to read an int and then test the result that it gives you to check that it is in the correct range. Something like this:
int number;
if (myScanner.hasNextInt()) {
number = myScanner.nextInt();
if (number < 0 || number > 100) {
// handle case where the number is out of range
}
} else {
// handle case where the input is not an integer
}
I will leave it to you to figure out how to map the above onto your application's requirements.
1 - The standard Scanner class doesn't provide a method that reads a number in a given range (and rejects numbers outside of that range). You could conceivably extend the Scanner class with this functionality, but it would be difficult. There are simpler solutions.
I would suggest you to write a function to get a valid input as below :-
public int getValidInput(Scanner in, int range) {
while (in.hasNext()) {
if (in.hasNextInt()) {
int val = in.nextInt();
if (val >= 0 && val < range) { // <-- from "0" to "range".
return val;
}
} else {
in.next();
}
}
return -1;
}
This function is ensuring that the input is given as an integer only and it lies in the range o to range. You can change it as per your requirement.
Consider this method:
static int getMark(String course){
int mark = 0;
boolean valid = true;
Scanner sc = new Scanner(System.in);
System.out.println("Enter marks obtained of " + course + ": ");
while(valid){
mark = sc.nextInt();
if(mark < 0 || mark > 100){
System.out.println("Mark must be between 0-100");
} else {
valid = true;
}
}
sc.close();
return mark;
}
This way you can get two birds with one stone, leaving the resulting code as this:
public static void main(String[] args){
int physics = getMark("Physics");
int chemistry = getMark("Chemistry");
int math = getMark("Math");
int english = getMark("English");
int computer = getMark("Computer Science");
float total = 500;
float obtained = (physics + chemistry + math + english + computer);
float percentage = (obtained / total) * 100;
System.out.println("The percentage obtained is: " + percentage);
}

Java using else if to assign a value [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm very new to programming and Java. I'm trying to use else if to assign a value to a variable if they selected the correct input. But whenever I try to compile it, it says it cannot find the variable.
import java.util.Scanner;
public class TDEE
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
double tdee = 0.0;
System.out.print("Please enter your name: ");
String name = in.next();
System.out.print("Please enter your BMR: ");
double bmr = in.nextDouble();
System.out.print("Please enter your Gender (M/F): ");
String gender = in.next();
System.out.println();
// providing menu items
System.out.println("Select your activity level: ");
System.out.println("[0] Resting (Sleeping. Reclining)");
System.out.println("[1] Sedentary (Minimal Movement)");
System.out.println("[2] Light (Sitting, Standing)");
System.out.println("[3] Moderate (Light Manual Labor, Dancing, Riding Bike)");
System.out.println("[4] Very Active (Team Sports, Hard Manual Labor)");
System.out.println("[5] Extremely Active (Full-time Athlete, Heavy Manual Labor)");
System.out.println();
// accept user choice with a Scanner class method
System.out.print("Enter the number corresponding to your activty level(0,1,2,3,4, or 5): ");
String choice = in.next();
System.out.println();
if(choice.equalsIgnoreCase("0"))
{
double activityFactor = 1.0;
}
else if(choice.equalsIgnoreCase("1"))
{
double activityFactor = 1.3;
}
else if(choice.equalsIgnoreCase("2") && "M".equals(gender))
{
double activityFactor = 1.6;
}
else if(choice.equalsIgnoreCase("2") && "F".equals(gender))
{
double activityFactor = 1.5;
}
else if(choice.equalsIgnoreCase("3") && "M".equals(gender))
{
double activityFactor = 1.7;
}
else if(choice.equalsIgnoreCase("3") && "F".equals(gender))
{
double activityFactor = 1.6;
}
else if(choice.equalsIgnoreCase("4") && "M".equals(gender))
{
double activityFactor = 2.1;
}
else if(choice.equalsIgnoreCase("4") && "F".equals(gender))
{
double activityFactor = 1.9;
}
else if(choice.equalsIgnoreCase("5") && "M".equals(gender))
{
double activityFactor = 2.4;
}
else if(choice.equalsIgnoreCase("5") && "F".equals(gender))
{
double activityFactor = 2.2;
}
else
{
System.out.println("You did not choose a valid manu option.");
}
tdee = bmr * activityFactor;
System.out.println();
System.out.println("Name: " + name + " Gender: " + gender);
System.out.println("BMR: " + bmr + " Activity Factor: " + activityFactor);
System.out.println("TDEE: " + tdee);
}
}
The reason it is not compiling is because of scoping. The variable you are declaring is inside an if statement. That gives its scope, ability to access it, to only within the if statement. In order to reference it outside the if statement, you must declare it within the scope you want to access it. Then you can assign values to it like as follows, activityFactor = 1.0;, within the if else statements. Where you declare your variables determines what can access them.
You have to declare double activityFactor outside of the if else statements. Just include double activityFactor; above the statements and replace all double activityFactor with activityFactor, and it should compile.

my program doesn't run completely [closed]

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 7 years ago.
Improve this question
For some reason, my program stops when it reaches the part that asks the user if it know it's exam 1 score. I need the user to be able to enter yes or no. Why does the program stop? I need it to work properly. I have all the if-else statements. I am able to enter the percentage weights, but that is all that the program will do. More must be done. My code extends far beyond entering the percentage weights. Please help me.
import java.util.Scanner;
public class GradeCalculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner grade = new Scanner (System.in);
// A new scanner must be created. The scanner is essential to this program performing properly.
double A = 90-100;
double B = 80-89;
double C = 70-79;
double D = 60-69;
double F = 0-59;
String LetterGrade;
String yes;
String no;
double Exam1, Exam2, finalExam, Labs, Projects, Attendance, Quizzes;
double Exam1Grade, Exam2Grade, finalExamGrade, LabAverage, ProjectsAverage, AttendanceAverage, QuizzesAverage;
double knownWeight;
double PercentageWeights;
// As always, the variables must be declared at the beginning of the program.
System.out.print(
"Grading Scale:\n"+
"A = 90-100 \n"+
"B = 80-89 \n"+
"C = 70-79 \n"+
"D = 60-69 \n"+
"F = 00-59 \n");
System.out.println("What letter grade do you want to achieve in this course?");
LetterGrade = grade.next();
// The user will type the letter grade that it wants in this part.
System.out.println("\nEnter Percentage Weights: \t");
String input = grade.nextLine();
// The string above is needed when the user enters the exam grades and averages.
System.out.print("\n\nExam 1: \t");
Exam1 = grade.nextShort();
System.out.print("\nExam 2: \t");
Exam2 = grade.nextShort();
System.out.print("\nFinal Exam: \t");
finalExam = grade.nextShort();
System.out.print("\nLabs: \t");
Labs = grade.nextShort();
System.out.print("\nProjects: \t");
Projects = grade.nextShort();
System.out.print("\nAttendance: \t");
Attendance = grade.nextShort();
System.out.print("\nQuizzes: \t");
Quizzes = grade.nextShort();
PercentageWeights = (int)(Exam1 + Exam2 + finalExam + Labs + Projects + Attendance + Quizzes);
// The equation above will provide the sum of the percentage weights. Since the variables in the equation were
// originally declared as doubles, I had to put "int" before the actual equation.
if (PercentageWeights > 100 || PercentageWeights < 100) {
System.out.println("\nWeights do not add up to 100. Program exiting. Have a nice day!");
System.exit(0);
}
else {
System.out.println("\nEnter your scores out of a 100: \t");
}
// The part above is very important to continue the rest of the program. If the sum of the percentage weights equals 100,
// the program will continue to run. If the sum is greater than or less than 100, the program will terminate.
System.out.print("\nDo you know your Exam 1 score?");
if (input.equalsIgnoreCase("yes")) {
System.out.print("\nScore received on Exam 1: ");
Exam1Grade = grade.nextDouble();
}
else{
Exam1Grade = 0;
}
System.out.print("\nDo you know your Exam 2 score?");
if (input.equalsIgnoreCase("yes")) {
System.out.print("\nScore received on Exam 2: ");
Exam2Grade = grade.nextDouble();
}
else{
Exam2Grade = 0;
}
System.out.print("\nDo you know your final exam score?");
if (input.equalsIgnoreCase("yes")){
System.out.print("\nScore received on final exam: ");
finalExamGrade = grade.nextDouble();
}
else{
finalExamGrade = 0;
}
System.out.print("\nDo you know your lab average?");
if (input.equalsIgnoreCase("yes")){
System.out.print("\nAverage lab grade: ");
LabAverage = grade.nextDouble();
}
else{
LabAverage = 0;
}
System.out.print("\nDo you know your project average?");
if (input.equalsIgnoreCase("yes")){
System.out.print("\nAverage project grade: ");
ProjectsAverage = grade.nextDouble();
}
else{
ProjectsAverage = 0;
}
System.out.print("\nDo you know your quiz average?");
if (input.equalsIgnoreCase("yes")) {
System.out.print("\nAverage quiz grade: ");
QuizzesAverage = grade.nextDouble();
}
else{
QuizzesAverage = 0;
}
System.out.print("\nDo you know your attendance average?");
if (input.equalsIgnoreCase("yes")){
System.out.print("\nAverage Attendance Grade: ");
AttendanceAverage = grade.nextDouble();
}
else{
AttendanceAverage = 0;
}
// The user has finished answering the questions. Now the program will automatically calculate the data based on
// what the user typed into the program.
double CurrentGrade, avgToFinalLetterGrade, WeightandGrade, finalOverallGrade;
// The doubles above need to be declared in order for the equations below to work properly.
WeightandGrade = (int)((Exam1 * Exam1Grade) + (Exam2 * Exam2Grade) + (finalExam * finalExamGrade) + (Labs * LabAverage) + (Projects * ProjectsAverage) + (Quizzes * QuizzesAverage) + (Attendance * AttendanceAverage));
CurrentGrade = (int)((WeightandGrade) / (Exam1 + Exam2 + finalExam + Labs + Projects + Quizzes + Attendance ));
knownWeight = (Exam1 + Exam2 + finalExam + Labs + Projects + Quizzes + Attendance);
if (grade.equals(A)){
finalOverallGrade = 90;
}
else if (grade.equals(B)){
finalOverallGrade = 80;
}
else if (grade.equals(C)){
finalOverallGrade = 70;
}
else if (grade.equals(D)){
finalOverallGrade = 60;
}
else
finalOverallGrade = F;
avgToFinalLetterGrade = (((100-finalOverallGrade) * (WeightandGrade)) / (100 - knownWeight));
// The equations above are one of the last parts of the program. These equations are critical to determine whether or not the user received its desired letter grade.
// If the desired grade was not reached, the program will give a score that the user must consistently receive in order to possibly reach the desired letter grade.
if (finalOverallGrade >= 90){
System.out.print("Congratulations! You got an A in the class! Hooray!");
}
else if (finalOverallGrade >=80 && finalOverallGrade < 90){
System.out.print("Good job. You got a B in the class!");
}
else if (finalOverallGrade >=70 && finalOverallGrade < 80){
System.out.print("You got a C in the class.");
}
else if (finalOverallGrade >=60 && finalOverallGrade < 70){
System.out.print("You got a D in the class.");
}
else
System.out.print("I'm sorry, but you have a failing grade in the class. May your GPA have mercy on your soul.");
}
}
There are quite a lot of things wrong with this code.
Doing double A=90-100; will set A equal to -10;
However, for your current question:
You do String input = grade.nextLine();
You never change input, and so if input isn't "yes", it will just skip getting the grades for each piece.
(You might want to also consult Using scanner.nextLine() for other pitfalls with using scanner.nextLine() intermixed with scanner.nextInt or similar [in summary: if you do scanner.nextInt, this doesn't consume the newline, so scanner.nextLine() will just get that newline and not the next line after that you might be expecting to get])
input = grade.nextLine() reads the remainder of the line with the user's "percentage weights" input on it. So unless the user had a priori knowledge to enter "yes", input will be empty.
I.e., you need to update input with user input before if (input.equalsIgnoreCase("yes")) {....

how to correctly use the OR operator java [closed]

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 8 years ago.
Improve this question
Hi I have been pullıng my hair out over this
I want this program to terminate if the user enters 0 or the running total = 20 exactly. When I try to compile I get an error:
here is my code - what an I doing wrong?
import java.util.Scanner;
public class RunningTotal
{
public static void main( String[] args)
{
Scanner keyboard = new Scanner(System.in);
int current = 1, total = 0;
System.out.print( "Type in a bunch of values and I'll add them up. ");
System.out.println( "I'll stop when you type a zero." );
do
{
System.out.print("Value: ");
current = keyboard.nextInt();
int newtotal = current + total;
total = newtotal;
System.out.println("The total so far is: " + total);
} while (current != 0) || (total != 20);
System.out.println("The final total is: " + total);
}
}
You got an error as you placed the brackets incorrectly
Here you have to use AND not OR.
do
{
System.out.print("Value: ");
current = keyboard.nextInt();
int newtotal = current + total;
total = newtotal;
System.out.println("The total so far is: " + total);
} while ((current != 0) && (total != 20));
Your while loop is missing an extra ( ) to wrap the OR conditions (each one needs to be in a bracket)
public class RunningTotal
{
public static void main( String[] args)
{
Scanner keyboard = new Scanner(System.in);
int current = 1, total = 0;
System.out.print( "Type in a bunch of values and I'll add them up. ");
System.out.println( "I'll stop when you type a zero." );
do
{
System.out.print("Value: ");
current = keyboard.nextInt();
int newtotal = current + total;
total = newtotal;
System.out.println("The total so far is: " + total);
} while ((current != 0) || (total != 20));
System.out.println("The final total is: " + total);
}
}
your while line is wrong it should be like this the expression in the while must be in braces () like this while(expression); and not like while(expression)||(expresion);
if you really want to use or this a solution
boolean notFinished = true;
do
{
System.out.print("Value: ");
current = keyboard.nextInt();
int newtotal = current + total;
total = newtotal;
System.out.println("The total so far is: " + total);
if (current==0 || total ==20){
notFinished=false;
}
} while (notFinished);
this is a Simpler Solution this is also correct because of de Morgans Law
while ((current != 0) && (total != 20));
this line should also work
while(current !=0 && total !=20);

Categories

Resources