Negative numbers are not recognized - java

import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
// Prints "Hello, World" in the terminal window.
Scanner quest = new Scanner(System.in);enter code here
System.out.println("How old are you?: ");
int num = quest.nextInt();
if (num <= 12){
System.out.println("You are too young to be on the computer!!!!");
} else if (num >=13 && num <= 17){
System.out.println("Welcome young teen");
} else if (17 < num && num <= 60){
System.out.println("Welcome adult");
} else if (60 < num){
System.out.println("Welcome senior citizen!!");
} else{
System.out.println("Invalid age.");
}
}
}
When I enter a negative number it just falls under the "You are too young to be on the computer!!!!" instead of displaying "Invalid age." I have tried changing the condition but it id not seem to work.

Because a negative number is less than 12, you could simplify your chain of if-else blocks by testing for negative values and eliminating your && checks by relying on the previously checked conditions. Like,
int num = quest.nextInt();
if (num < 0) { // <-- negative values.
System.out.println("Invalid age.");
} else if (num <= 12) { // <-- (0, 12)
System.out.println("You are too young to be on the computer!!!!");
} else if (num <= 17) { // <-- (13, 17)
System.out.println("Welcome young teen");
} else if (num <= 60) { // <-- (18, 60)
System.out.println("Welcome adult");
} else { // <-- greater than 60
System.out.println("Welcome senior citizen!!");
}

You should have made it your first condition with the if(Condition) { //Code } statement. Well I did a run on the code and kinda make a little adjustment to your code.
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
// Prints "Hello, World" in the terminal window.
Scanner quest = new Scanner(System.in); //enter code here
System.out.println("How old are you?: ");
int num = quest.nextInt();
if (num <= 0) {
System.out.println("Invalid age.");
} else if (num <= 12){
System.out.println("You are too young to be on the computer!!!!");
} else if (num >=13 && num <= 17){
System.out.println("Welcome young teen");
} else if (17 < num && num <= 60){
System.out.println("Welcome adult");
} else if (60 < num){
System.out.println("Welcome senior citizen!!");
}
}
}

Related

Variable not being recognized in method

I am relatively new to Java, and I am writing a simple program to play rock, paper, scissors. This is the code:
import java.util.Random;
import java.util.Scanner;
public class Main {
public static String comChoice() {
Random rand = new Random();
int num = rand.nextInt(299) + 1;
if (num >= 1 && num <= 99) {
String pick = "SCISSORS";
} else if (num >= 100 && num <= 199) {
String pick = "ROCK";
} else if (num >= 200 && num <= 299) {
String pick = "PAPER";
}
return pick;
}
public static void main(String args[]) {
int wins = 0;
int losses = 0;
int ties = 0;
while (1 == 1) {
Scanner s = new Scanner(System.in);
System.out.println("Would you like to play Rock Paper Scissors? Y/N");
String n = s.next();
if (n.equalsIgnoreCase("Y")) {
Scanner t = new Scanner(System.in);
System.out.println("Enter your pick: rock, paper, or scissors");
String userChoice = t.next();
String pick = comChoice();
if (userChoice.equalsIgnoreCase("SCISSORS") && pick.equalsIgnoreCase("SCISSORS")) {
System.out.println("TIE");
ties++;
} else if (userChoice.equalsIgnoreCase("ROCK") && pick.equalsIgnoreCase("SCISSORS")) {
System.out.println("WIN");
wins++;
} else if (userChoice.equalsIgnoreCase("PAPER") && pick.equalsIgnoreCase("SCISSORS")) {
System.out.println("LOSE");
losses++;
} else if (userChoice.equalsIgnoreCase("SCISSORS") && pick.equalsIgnoreCase("ROCK")) {
System.out.println("LOSE");
losses++;
} else if (userChoice.equalsIgnoreCase("SCISSORS") && pick.equalsIgnoreCase("PAPER")) {
System.out.println("WIN");
wins++;
} else {
System.out.println("Enter a valid choice");
}
} else {
System.out.println("You won " + wins + " matches");
System.out.println("You tied " + ties + " matches");
System.out.println("You lost " + losses + " matches");
break;
}
}
}
}
I'm getting an error in my method which says this:
Main.java:23: error: cannot find symbol
return pick;
^
symbol: variable pick
location: class Main
1 error
exit status 1
I can't figure out how to fix this error. I would appreciate your input as well as any other general advice
Thanks
Your variable is only visible in the if statement. Read about scopes.
Change to:
import java.util.Scanner;
import java.util.Random;
public class Main {
public static String comChoice() {
Random rand = new Random();
int num = rand.nextInt(299) + 1;
String pick = null;
if (num >= 1 && num <= 99) {
pick = "SCISSORS";
} else if (num >= 100 && num <= 199) {
pick = "ROCK";
} else if (num >= 200 && num <= 299) {
pick = "PAPER";
}
return pick;
}
....
}
pick is out of scope. Try declaring at the start of the comChoice method.
Hence :
public static String comChoice() {
String pick=null;
Random rand = new Random();
int num = rand.nextInt(299) + 1;
if (num >= 1 && num <= 99) {
pick = "SCISSORS";
} else if (num >= 100 && num <= 199) {
pick = "ROCK";
} else if (num >= 200 && num <= 299) {
pick = "PAPER";
}
return pick;
}
variable pick is out of scope. You have to declare it outside the all if else statements. if all if else condition fail then comChoice method will not be able to find variable pick (as it is declared inside the if else block only)which it has to return.
corrected code
import java.util.Scanner;
import java.util.Random;
public class Main
{
public static String comChoice()
{
Random rand = new Random();
int num = rand.nextInt(299) + 1;
String pick = "";
if(num >= 1 && num <= 99)
{
pick = "SCISSORS";
}
else if (num >= 100 && num <= 199)
{
pick = "ROCK";
}
else if (num >= 200 && num <= 299)
{
pick = "PAPER";
}
return pick;
}
public static void main (String args[])
{
int wins = 0;
int losses = 0;
int ties = 0;
while (1 == 1)
{
Scanner s = new Scanner (System.in);
System.out.println("Would you like to play Rock Paper Scissors? Y/N");
String n = s.next();
if (n.equalsIgnoreCase("Y"))
{
Scanner t = new Scanner (System.in);
System.out.println("Enter your pick: rock, paper, or scissors");
String userChoice = t.next();
String pick = comChoice();
if (userChoice.equalsIgnoreCase("SCISSORS") && pick.equalsIgnoreCase("SCISSORS"))
{
System.out.println("TIE");
ties++;
}
else if (userChoice.equalsIgnoreCase("ROCK") && pick.equalsIgnoreCase("SCISSORS"))
{
System.out.println("WIN");
wins++;
}
else if (userChoice.equalsIgnoreCase("PAPER") && pick.equalsIgnoreCase("SCISSORS"))
{
System.out.println("LOSE");
losses++;
}
else if (userChoice.equalsIgnoreCase("SCISSORS") && pick.equalsIgnoreCase("ROCK"))
{
System.out.println("LOSE");
losses++;
}
else if (userChoice.equalsIgnoreCase("SCISSORS") && pick.equalsIgnoreCase("PAPER"))
{
System.out.println("WIN");
wins++;
}
else
{
System.out.println("Enter a valid choice");
}
}
else
{
System.out.println("You won " + wins + " matches");
System.out.println("You tied " + ties + " matches");
System.out.println("You lost " + losses + " matches");
break;
}
}
}
}
You declared your variable pick in the if else structure. Doing this causes the problem that your variable cannot be accessed from outside that if else structure. In simple words, the variable pick's scope is limited to your if else structure. You have to declare your variable (and initialize it as well, otherwise you'll get an error in your case) outside of the if else structure. Like this:
String pick = null;
if(num >= 1 && num <= 99) {
...
...
...// All your if's and else's
}
return pick;
Hope this helps!

How do I end the console if the user inputs an integer than doesn't comply with my condition?

I'm currently create a simple grade calculator, however I want the console not to continue with the next line when the user doesn't enter a number between 0 and 20. Even if the user enters the wrong one the next line is executed. Also feel free to suggest ways of making my program simpler.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter grade for Exam 1:>");
int exam1 = scanner.nextShort();
while (exam1 > 20 || exam1 < 0) {
System.out.println("Error! Not within mark range!");
break;
}
System.out.println("Enter grade for Exam 2:>");
int exam2 = scanner.nextShort();
while (exam2 > 20 || exam2 < 0) {
System.out.println("Error! Not within mark range!");
break;
}
System.out.println("Enter grade for Exam 3:>");
int exam3 = scanner.nextShort();
while (exam3 > 20 || exam3 < 0) {
System.out.println("Error! Not within mark range!");
break;
}
System.out.println("Enter grade for Exam 4:>");
int exam4 = scanner.nextShort();
while (exam4 > 20 || exam4 < 0) {
System.out.println("Error! Not within mark range!");
break;
}
int average = exam1 + exam2 + exam3 + exam4;
average /= 4;
System.out.println("You average grade is: " + average + "\n");
average *= 5;
System.out.println("Your score is" + average + "%!\n");
if (average > 70) {
System.out.println("You get an A overall");
} else if (average > 60 || average <= 70) {
System.out.println("You get a B overall");
} else if (average > 40 || average <= 60) {
System.out.println("You get a C overall");
} else {
System.out.println("You have failed the module!");
}
}
}
System.exit(0);
This is probably what you're looking for, instead of the break statements.
Replace the break statements in your code with System.exit(0)

A while loop that stops after a certian number is entered

I am trying to write a program that takes in grades numbers from the user, and stops when -1 is entered. But, every time I enter -1 the while loop continues to run, how do I stop it from running?
import java.util.Scanner;
public class getLetterGrade {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int count = 0;
while (count >= 0)
getGrade();
count++;
System.out.println("You entered" + " " + count + " " + "Student(s)");
}
public static void getGrade() {
Scanner reader = new Scanner(System.in);
double grade;
System.out.println("Welcome to the grade calculator. \n Please enter a numeric grade. \n After the last student in the class, enter a grade of -1.");
grade = reader.nextDouble();
if (grade >= 90)
System.out.println("That's an A");
else if (grade >= 80 && grade < 90)
System.out.println("That's an B");
else if (grade >= 70 && grade < 80)
System.out.println("That's an C");
else if (grade >= 60 && grade < 70)
System.out.println("That's an D");
else if (grade <= 50 && grade > 0)
System.out.println("That's an F");
if (grade == -1)
System.out.println("");
}
}
A few things that need to be changed... First, your loop keeps looping because you never set count to less then 0, so the condition is always true. You also create 2 Scanner objects, but only ever use the second one (in getGrade()).
Try this code, and have a look at the comments to see everything that's changed:
public class getLetterGrade {
static Scanner reader; //Add reader as member variable
public static void main(String[] args) {
//Scanner reader = new Scanner(System.in); //Remove this unused Scanner
int count = 0;
reader = new Scanner(System.in);
while (getGrade()) //Change the condition here so the loop will continue while getGrade() returns true.
count++;
reader.close(); //Close the Scanner
System.out.println("You entered" + " " + count + " " + "Student(s)");
}
public static boolean getGrade() { //getGrade() returns a boolean...
System.out.println("Welcome to the grade calculator. \n Please enter a numeric grade. \n After the last student in the class, enter a grade of -1.");
double grade = reader.nextDouble(); //Consider using a try/catch block here.
if (grade >= 90)
System.out.println("That's an A");
else if (grade >= 80 && grade < 90)
System.out.println("That's an B");
else if (grade >= 70 && grade < 80)
System.out.println("That's an C");
else if (grade >= 60 && grade < 70)
System.out.println("That's an D");
else if (grade <= 50 && grade > 0)
System.out.println("That's an F");
else if(grade != -1)
System.out.println("Invaled input!"); //Print if 'grade' is something other then the above statements.
if (grade == -1) { //Add brackets
System.out.println("");
return false; //return false if -1 was entered...
}
return true; //else return true
}
}
You could move the loop down into the other method, make it an "endless" loop, and use return to exit from it. You can then return the count from that method and show it in main.
It might then look like this. Note that I've simplified your branching logic too, and removed the double entendre from the output message.
I have also used a try-with-resources block, which is one way of making sure you always close the scanner, and avoid resource leaks. Not strictly needed in this case, but still a good habit to get into.
Edit As the Scary Wombat has pointed out, you could add an else clause to deal with the case where the user inputs an invalid grade if you really wanted to.
import java.util.Scanner;
public class GetLetterGrade {
public static void main(String[] args) {
int count = getGrades();
System.out.println("You entered " + count + " grade(s)");
}
public static int getGrades() {
try(Scanner reader = new Scanner(System.in)) {
int count = 0;
while(true) {
System.out.println("Welcome to the grade calculator. \n Please enter a numeric grade. \n After the last student in the class, enter a grade of -1.");
double grade = reader.nextDouble();
if (grade >= 90) {
System.out.println("That's an A");
} else if (grade >= 80 ) {
System.out.println("That's a B");
} else if (grade >= 70) {
System.out.println("That's a C");
} else if (grade >= 60) {
System.out.println("That's a D");
} else if (grade >= 0) {
System.out.println("That's an F");
} else if (grade == -1) {
return count;
}
count++;
}
}
}
}
import java.util.Scanner;
public class GetLetterGrade {
public static void main(String[] args) {
int count = 0;
while (getGrade() >= 0.0){
count++;
System.out.println("You entered" + " " + count + " " + "Student(s)");
}
}
public static double getGrade() {
Scanner reader = new Scanner(System.in);
double grade;
System.out.println("Welcome to the grade calculator. \n Please enter a numeric grade. \n After the last student in the class, enter a grade of -1.");
grade = reader.nextDouble();
if (grade >= 90)
System.out.println("That's an A");
else if (grade >= 80 && grade < 90)
System.out.println("That's an B");
else if (grade >= 70 && grade < 80)
System.out.println("That's an C");
else if (grade >= 60 && grade < 70)
System.out.println("That's an D");
else if (grade <= 50 && grade > 0)
System.out.println("That's an F");
if (grade == -1)
System.out.println("");
return grade ;
}
}
Your while loop always takes the 0 value and get in to while loop thats why it didn't stop..
import java.util.Scanner;
public class getLetterGrade {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Welcome to the grade calculator. \n After the last student in the class, enter a grade of -1.");
int count = 0;
int no = -1;
while (count != -1) {
no++;
System.out.println("Please enter the value:-");
count = reader.nextInt();
if (count >= 90) {
System.out.println("That's an A");
} else if (count >= 80 && count < 90) {
System.out.println("That's an B");
} else if (count >= 70 && count < 80) {
System.out.println("That's an C");
} else if (count >= 60 && count < 70) {
System.out.println("That's an D");
} else if (count <= 59 && count > 0) {
System.out.println("That's an F");
}
if (count == -1) {
break;
}
}
count++;
System.out.println("You entered" + " " + no + " " + "Student(s)");
}
}

Java using if statement, for loop and method call

In main, create a for loop that will ask for the numeric grade and uses the getLetterGrade method to print out the letter grade, until the user enters a -1. so practically i have to ask the user to enter the grade between 0 and 100 and it will look in the method and print the appropriate grade? correct??? so here's the code
System.out.println("Please enter you grade total: ");
Scanner Keyboard = new Scanner(System.in);
studentGrade = Keyboard.nextInt();
for(studentGrade = 0; studentGrade < 1; ++studentGrade){
System.out.print(getLetterGrade);
Create a method called getLetterGrade. The getLetterGrade method takes a grade between 0-100 and then prints out the corresponding letter grade. The grade ranges are A: 100-90 B: 80-89 C: 70-79, D: 60-69, F: 0-59. In main, create a for loop that will ask for the numeric grade and uses the getLetterGrade method to print out the letter grade, until the user enters a -1."
Here's my code: I wrote using if,else if condition. what i don't understand is that do i have to write the condition in main or the method. Usually i dont have a problem with coding but this thing has me puzzled. I though about using case but if, else if conditions seems alot more straight forward.
import java.util.Scanner;
public class getLetterGrade {
public static void getLetterGrade(String getLetterGrade){
int studentGrade = 0;
if(studentGrade >= 90) getLetterGrade("A");
else if(studentGrade >= 80) getLetterGrade("B");
else if(studentGrade >= 70) getLetterGrade("C");
else if(studentGrade >= 60) getLetterGrade("D");
else if(studentGrade >= 0) getLetterGrade("F");
else
System.out.println("you have entered incorrect integer");
int i = 0;
for (i = 0; i < 1; i++){
System.out.print(studentGrade + " ");
}
System.out.println();
}
public static void main(String[] args) {
int studentGrade = 0;
getLetterGrade("A");
getLetterGrade("B");
getLetterGrade("C");
getLetterGrade("D");
getLetterGrade("F");
System.out.println("Please enter you grade total: ");
Scanner Keyboard = new Scanner(System.in);
studentGrade = Keyboard.nextInt();
for(studentGrade = 0; studentGrade < 1; ++studentGrade){
System.out.print(studentGrade);
}
}
}
i know i have to print getLetterGrade but when i try to print getLetterGrade it throws errors, i dont get it.....
thanks for any and all help!!
Your getLetterGrade method is recursive. In the method, you set studentGrade=0, so the method calls getLetter("A"). This repeats, which results in a stackoverflow error.
I think this is what you want instead:
public static void getLetterGrade (int studentGrade) {
if (studentGrade >= 90) System.out.println("A");
else if (studentGrade >= 80) System.out.println("B");
else if (studentGrade >= 70) System.out.println("C");
else if (studentGrade >= 60) System.out.println("D");
else if (studentGrade >= 0) System.out.println("F");
else System.out.println("You have entered an incorrect integer.");
}
In your main method, I think this is what you want:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int studentGrade = keyboard.nextInt();
while (studentGrade != -1) {
getLetterGrade(studentGrade);
studentGrade = keyboard.nextInt();
}
}
In the main method, you can't use a for loop because you don't know in advance how many times the user wants to input. The while loop, on the other hand, checks that the input is not -1 and then prints out the grade for each iteration.
You might need to see a tutorial about for loops though. In a for loop, the variable is just an index. It doesn't have the value of whatever it is you assign to it previously.
try this .
package com.health;
import java.util.Scanner;
public class Test {
public static void getLetterGrade(int studentGrade) {
// int studentGrade = 0;
if (studentGrade >= 90)
System.out.println("A");
else if (studentGrade >= 80)
System.out.println("B");
else if (studentGrade >= 70)
System.out.println("C");
else if (studentGrade >= 60)
System.out.println("D");
else if (studentGrade >= 0)
System.out.println("E");
else
System.out.println("you have entered incorrect integer");
// int i = 0;
//
// for (i = 0; i < 1; i++) {
// System.out.print(studentGrade + " ");
// }
//
// System.out.println();
}
public static void main(String[] args) {
int studentGrade = 0;
// getLetterGrade("A");
// getLetterGrade("B");
// getLetterGrade("C");
// getLetterGrade("D");
// getLetterGrade("F");
while (true) {
System.out.println("Please enter you grade total: ");
Scanner Keyboard = new Scanner(System.in);
studentGrade = Keyboard.nextInt();
if (studentGrade == -1) {
break;
} else {
getLetterGrade(studentGrade);
}
}
// for (studentGrade = 0; studentGrade < 1; ++studentGrade) {
// System.out.print(studentGrade);
// }
}
}

While loop output

The program will generate the correct output for the first number guess but after the user inputs the second guess, there is no output at all. Please help! THANKS
final int number = (int)((Math.random()*99)+1);
int counter = 0;
System.out.print("Enter a guess between 1 and 100: ");
while (keyboard.nextInt() > number) {
System.out.println("Your guess was too high. Try again.");
counter++;
System.out.print("Enter a guess between 1 and 100: ");
}
while (keyboard.nextInt() < number) {
System.out.println("Your guess was too low. Try again.");
counter++;
System.out.print("Enter a guess between 1 and 100: ");
}
while (keyboard.nextInt() == number) {
System.out.println("Congratulations! Your guess was correct!");
counter++;
System.out.println("I had chosen " + number + " as the target number.");
System.out.println("You guessed it in " + counter + " tries.");
if (counter == 1) {
System.out.println("That was lucky!");
}
if (counter >= 2 || counter <= 4) {
System.out.println("That was amazing!");
}
if (counter == 5 || counter == 6) {
System.out.println("That was good.");
}
if (counter == 7) {
System.out.println("That was OK.");
}
if (counter == 8 || counter == 9) {
System.out.println("That was not very good.");
}
if (counter >= 10) {
System.out.println("This just isn't your game.");
}
you really need to change your design pattern.
Once you fail to satisfy the conditions in 1 of those while loops, you code will never go back.
you should only have 1 while loop for the guessing phase. you code should look like this
while(someCondition)
{
int num = keyboard.nextInt()
if (num > number) {
...
}
else if (num < number) {
...
}
else if (num == number) {
...
}
}
Your while loops should be if statements.
There should be a while loop around (practically) all your code
You code should roughly look like:
while(true) {
// prompt for input
// read input
// break from loop if input is the exit input, eg -1
// check input - essentially change your whiles to ifs
}
This block doesn't seem to work as intended:
while (keyboard.nextInt() > number) {
System.out.println("Your guess was too high. Try again.");
counter++;
System.out.print("Enter a guess between 1 and 100: ");
}
while (keyboard.nextInt() < number) {
System.out.println("Your guess was too low. Try again.");
counter++;
System.out.print("Enter a guess between 1 and 100: ");
}
Assume the user enters -1 and then 101. You'll end up in the next loop. Thus you might want to change it to something like this:
boolean retry = true;
while ( retry ) {
counter++;
int n = keyboard.nextInt();
if( n > number ) {
System.out.println("Your guess was too high. Try again.");
}
else if( n < number ) {
System.out.println("Your guess was too low. Try again.");
}
else {
//number found
retry = false;
}
if( retry ) {
System.out.prnt("Enter a guess between 1 and 100: ");
}
}
There is some problem in how you use the while statement.
Here you can find the correct version of your code:
public static void main(final String[] args) {
final Scanner keyboard = new Scanner(System.in);
final int number = (int) ((Math.random() * 99) + 1);
int counter = 0;
System.out.print("Enter a guess between 1 and 100: ");
int user_number;
do {
user_number = keyboard.nextInt();
if (user_number > number) {
System.out.println("Your guess was too high. Try again.");
System.out.print("Enter a guess between 1 and 100: ");
counter++;
} else if (user_number < number) {
System.out.println("Your guess was too low. Try again.");
System.out.print("Enter a guess between 1 and 100: ");
counter++;
}
} while (user_number != number);
System.out.println("Congratulations! Your guess was correct!");
counter++;
System.out.println("I had chosen " + number + " as the target number.");
System.out.println("You guessed it in " + counter + " tries.");
if (counter == 1) {
System.out.println("That was lucky!");
}
if ((counter >= 2) || (counter <= 4)) {
System.out.println("That was amazing!");
}
if ((counter == 5) || (counter == 6)) {
System.out.println("That was good.");
}
if (counter == 7) {
System.out.println("That was OK.");
}
if ((counter == 8) || (counter == 9)) {
System.out.println("That was not very good.");
}
if (counter >= 10) {
System.out.println("This just isn't your game.");
}
}
while(someCondition)
{
if (keyboard.nextInt() > number) {
...
} else if(keyboard.nextInt() < number) {
...
} else {
...
}
}

Categories