How to use method variables in main? - java

For my school I need to create a method which moves a bug in any direction. I have the following code:
package Test;
//imports
import java.util.Scanner;
import java.util.Random;
public class test {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
ABug[] BugObj = new ABug[4]; //Creating object BugObj of class ABug
int loop = 1;
int i = 0;
do {
BugObj[i] = new ABug(); //creating instance
System.out.println("Please enter the name of the bug:");
BugObj[i].name = reader.next();
System.out.println("Please enter the species of the bug:");
BugObj[i].species = reader.next();
System.out.println("Please enter the horizontal position of the bug:");
BugObj[i].horpos = reader.nextInt();
System.out.println("Please enter the vertical postion of the bug:");
BugObj[i].vertpos = reader.nextInt();
System.out.println("_______________ Bug " +(+i+1) + " _______________\n" );
System.out.println("Name: " + BugObj[i].name); //Printing bug information out
System.out.println("Species: " + BugObj[i].species);
System.out.println("Horizontal Position: " + BugObj[i].horpos);
System.out.println("Vertical Postion: " + BugObj[i].vertpos + "\n\n");
move();
i++;
System.out.println("Would you like to enter another bug? \n 0-No, 1-Yes\n");
loop = reader.nextInt();
} while(loop == 1);
}
public static void move() {
Scanner reader = new Scanner(System.in);
System.out.println("Would you like this bug to move?\n 0-No, 1-Yes\n");
if (reader.nextInt() == 0) {
System.exit(0);
}
int r = (int) (Math.random() * (2- -2)) + -2;
System.out.println(r);
}
}
class ABug { //ABug class
int horpos, vertpos, energy, id;
char symbol;
String species, name;
}
Basically all I need to do is use the values of the bugs position with the random number generated in the method. I am really new to java and am unsure how to do it or even if its possible.

Since objects are passed by reference in java, you can just pass your ABug object to the move function and change the horpos, vertpos attributes. so
move(BugObj[i]);
and
public static void move(ABug bug){
Scanner reader = new Scanner(System.in);
System.out.println("Would you like this bug to move?\n 0-No, 1-Yes\n");
if (reader.nextInt() == 0)
{
System.exit(0);
}
int r = (int) (Math.random() * (2- -2)) + -2;
int originalHorpos = bug.horpos
int originalVertpos = bug.vertpos
// Now just change the attributes however you see fit. i am just adding r
bug.horpos = originalHorpos + r;
bug.vertpos = originalVertpos + r
/*by the way, we dont need to use variables for the original values. something like this would also work
bug.horpos += r;
bug.vertpos += r;
i just want to explain that in java when you pass objects, they are passed by reference and hence you have access to all of its members.
*/
System.out.println(r);
}
also, you dont need to declare the Scanner object again inside the move function. you can pass that to the move function as well and then read as many times as you like.

Related

cannot find symbol error in condition of while loop

I'm writing a program for an assignment that should give random problems for the user to solve. what I am attempting to make it do is after selecting a problem type and answering one question the program should load the menu up again.
Originally I wrote a method that would be called in the else statement on line 147. The method successfully looped however the assignment specifically asks for a loop to make it happen. I've tried several different ways to change the loops condition statement but I'm not sure where I went wrong? any help would be appreciated.
I want very badly to use a switch statement but I can't as we haven't learned that in class.
// Importing Scanner and Random class for later.
import java.util.Scanner;
import java.util.Random;
class AlgebraTutor {
// Solve for Y method.
public static void solve_for_y() {
// Creation of a random number generator.
Random number_gen = new Random();
// Generates random integers from -100 to 100.
int var_m = number_gen.nextInt(101) - 100;
int var_x = number_gen.nextInt(101) - 100;
int var_b = number_gen.nextInt(101) - 100;
// Print problem out for student to see
System.out.println("Problem: y = " + var_m + "(" + var_x +")" + "+" + var_b);
System.out.println(" m =" + var_m);
System.out.println(" x =" + var_x);
System.out.println(" b =" + var_b);
// This formula will calculate the value of y.
float var_y = (var_m * var_x) + var_b;
// Using the scanners class a scanner object called userInput was created to record students answer. Answer was taken as a string and converted to an integer.
Scanner user_input = new Scanner(System.in);
System.out.println("Please solve for y:");
String user_answer = user_input.nextLine();
int answer = Integer.parseInt(user_answer);
if (answer == var_y){
System.out.println("correct");
}else{
System.out.println("incorrect, The answer is:" + var_y);
}
}
// -------------------------------------------------------------------------
// Solve for M method.
public static void solve_for_m() {
// Creation of a random number generator.
Random number_gen = new Random();
// Generates random integers from -100 to 100.
int var_y = number_gen.nextInt(101) - 100;
int var_x = number_gen.nextInt(101) - 100;
int var_b = number_gen.nextInt(101) - 100;
// Print problem out for student to see.
System.out.println("Problem: " + var_y + " = m (" + var_x +") + " + var_b);
System.out.println(" y =" + var_y);
System.out.println(" x =" + var_x);
System.out.println(" b =" + var_b);
// This formula will calculate the value of m.
float var_m = (var_y - var_b) / var_x;
// Using the scanners class a scanner object called userInput was created to record students answer. Answer was taken as a string and converted to an integer.
Scanner user_input = new Scanner(System.in);
System.out.println("Please solve for m:");
String user_answer = user_input.nextLine();
int answer = Integer.parseInt(user_answer);
if (answer == var_m){
System.out.println("correct");
}else{
System.out.println("incorrect, The answer is:" + var_m);
}
}
// -------------------------------------------------------------------------
// Solve for B method
public static void solve_for_b() {
// Creation of a random number generator.
Random number_gen = new Random();
// Generates random integers from -100 to 100.
int var_y = number_gen.nextInt(101) - 100;
int var_x = number_gen.nextInt(101) - 100;
int var_m = number_gen.nextInt(101) - 100;
// Print problem out for student to see.
System.out.println("Problem: " + var_y + " = " + var_m + " (" + var_x +") " + "+ b");
System.out.println(" y =" + var_y);
System.out.println(" x =" + var_x);
System.out.println(" m =" + var_m);
// This formula will calculate the value of m.
float var_b = var_y / (var_m * var_x);
// Using the scanners class a scanner object called userInput was created to record students answer. Answer was taken as a string and converted to an integer.
Scanner user_input = new Scanner(System.in);
System.out.println("Please solve for b:");
String user_answer = user_input.nextLine();
int answer = Integer.parseInt(user_answer);
if (answer == var_b){
System.out.println("correct");
}else{
System.out.println("incorrect, The answer is:" + var_b);
}
}
// -------------------------------------------------------------------------
public static void main(String[] args) {
do{
System.out.println("Which type of problem would you like to practice?");
System.out.println("1) Solve for y");
System.out.println("2) Solve for m");
System.out.println("3) Solve for b");
System.out.println("4) To quit");
Scanner selection_input = new Scanner(System.in);
String user_selection = selection_input.nextLine();
if ( user_selection.equals("1")){
solve_for_y();
} else if (user_selection.equals("2")){
solve_for_m();
} else if (user_selection.equals("3")){
solve_for_b();
} else if (user_selection.equals("4")){
System.out.println("Quitting Program");
System. exit(0);
} else{
System.out.println("Please choose from the given options");
}
} while(user_selection.equals("1") &&
user_selection.equals("2") &&
user_selection.equals("3") &&
user_selection.equals("4"));
}
}
You must declare the user_inpout variable outside the do...while loop, then you can check its value in the while() expression. Also you should initialize the scanner only once at the beginning of your program.
public static void main(String[] args)
{
Scanner selection_input = new Scanner(System.in);
String user_selection=null;
do
{
System.out.println("Which type of problem would you like to practice?");
System.out.println("1) Solve for y");
System.out.println("2) Solve for m");
System.out.println("3) Solve for b");
System.out.println("4) To quit");
user_selection = selection_input.nextLine();
if (user_selection.equals("1"))
{
solve_for_y();
}
else if (user_selection.equals("2"))
{
solve_for_m();
}
else if (user_selection.equals("3"))
{
solve_for_b();
}
else if (user_selection.equals("4"))
{
System.out.println("Quitting Program");
System.exit(0);
}
else
{
System.out.println("Please choose from the given options");
}
}
while (!user_selection.equals("4"));
}
For the case "4" you have two exists now:
else if (user_selection.equals("4"))
{
System.out.println("Quitting Program");
System.exit(0);
}
and:
while (!user_selection.equals("4"));
Only one of both is needed. So you may either remove the first one or replace the while statement by while(true).

Java: Missing return statement for a math quiz?

New to Java. The task is to Create a MathQuiz application that asks the user whether they would like a simple or difficult math quiz and the number of questions they would like to answer. The application then displays the questions, one at a time,prompting the user for the answer and confirming whether or not the answer is correct. The MathQuiz application should include separate methods for the simple and difficult math quiz.The simple() method should display addition problems. The difficult() method should display multiplication problems. Random numbers should be generated for the quiz questions. This is what I have so far:
import java.util.Scanner;
public class MathQuiz {
public static double simple() {
int randomNumber1 = (int)(20 * Math.random()) + 1;
int randomNumber2 = (int)(20 * Math.random()) + 1;
int randomNumberAdd = randomNumber1 + randomNumber2;
//user input
Scanner keyboard = new Scanner(System.in);
System.out.print(randomNumber1 + " + " + randomNumber2 + " = ");
int GuessRandomNumberAdd = keyboard.nextInt();
if (GuessRandomNumberAdd == randomNumber1 + randomNumber2) {
System.out.println("Correct!");
}else {
System.out.println("Wrong. The correct answer is " + randomNumberAdd);
}
}
public static double difficult() {
int randomNumber1 = (int)(20 * Math.random()) + 1;
int randomNumber2 = (int)(20 * Math.random()) + 1;
int randomNumberMul = randomNumber1 * randomNumber2;
int correct = 0;
//user input
Scanner keyboard = new Scanner(System.in);
System.out.print(randomNumber1 + " * " + randomNumber2 + " = ");
int GuessRandomNumberMul = keyboard.nextInt();
if (GuessRandomNumberMul == randomNumber1 * randomNumber2) {
System.out.println("Correct!");
}else{
System.out.println("Wrong. The correct answer is " + randomNumberMul);
}
}
//user options
public static void main(String[] args) {
int choice;
Scanner input = new Scanner(System.in);
System.out.println("There are two levels available:");
System.out.println("1. Simple");
System.out.println("2. Difficult");
System.out.print("Enter your choice: ");
choice = input.nextInt();
if (choice == 1) {
simple();
} else if (choice == 2) {
difficult();
}
input.close();
}
}
public static double simple() {}
public -> It specifies the access level of this function.
static -> It means this function is a behavior of your class and not specific to any instance of this class.
double -> It's what your function returns, a double typed value here, as an output at end of execution.
simple()-> It's your function name
In both of your functions simple() and difficult() you are not returning any value as output. So you have to change it to void.
Change your method simple() and difficult() return type from double to void and the error should go away
Change the return type of simple() and double() method to void, i.e.
public static void simple() and
public static void difficult()
The return type of these methods is currently double, so it is expected to return a double value. If they don't return a double value, the compiler will give you an error. So, if you don't plan to return a value in your methods, change the return type to void.
Removing the return type of double from your method's signature and setting it to void, the error should go away.
public static void simple() {
// your code
}
public static void difficult() {
// your code
}

Creating Methods that will produce the same result

I'm in a Beginner Java class and I'm confused about using additional methods and using them in another. I think that I have most of my assignment done but I just need help to create the methods. One is to generate the question and the other one is to display the message.
I know that in order to call a method
public static test(num1,num2,num3)
but in my code, how do I make it so that I call the method and still make it loop correctly?
In the assignment instructions that was given to me, In order to do that, I have to write a method named
public static in generateQuestion()
and
public static void displayMessage(boolean isCorrect)
This is my code:
//For Random Generator
import java.util.Random;
//Uses a class Scanner
import java.util.Scanner;
public class Assign6
{
public static void main(String[] args)
{
//Scanner to Obtain Input from CW
Scanner input = new Scanner(System.in);
//Generate Random Number for Quiz
Random randomNumbers = new Random();
int number1 = 0;
int number2 = 0;
int answer = 0;
//Rolls number from 1-9
number1 = randomNumbers.nextInt(9);
number2 = randomNumbers.nextInt(9);
//Question prompt
System.out.println("How much is " +number1+ " times " +number2+ "? ");
answer = input.nextInt();
//If Else While Statements
if(answer == (number1*number2))
{
System.out.println("Good job! You got it right!");
}
else
{
while (answer !=(number1*number2))
{
System.out.println("You got it wrong, try again!");
answer = input.nextInt();
}
}
}
}
You are going to have two methods
public static void generateQuestion()
Which is going to hold the code to generate the random values and output it. It will return void because all it's doing is printing out.
Next you will have
public static void displayMessage(boolean isCorrect)
which will be called if if(answer == (number1*number2)) is true with true as the parameter. Otherwise it will still be called, but the parameter passed in will be false. This method will determine if isCorrect is true or false, and output the appropriate message.
If I got it right, I have a solution that might be a little stupid but will work for your assignment.
If you make generateQuestion that makes two random ints, prints the question and returns their multiple (answer).
And displayMessgae that prints "Good job! You got it right!" if isCorrect is true and "You got it wrong, try again!" else,
you can call generateQuestion, then get an answer (in main), and loop until answer is correct (according to return value of generateQuestion).
Every time you get a new answer (in loop), call displayMessgae(false).
After the loop ended call displayMessgae(true)
This is my working code for this:
//For Random Generator
import java.util.Random;
//Uses a class Scanner
import java.util.Scanner;
public class Assign6
{
public static int generateQuestion()
{
Random r = new Random();
int x = r.nextInt(9), y = x = r.nextInt(9);
System.out.println("How much is " + x + " times " + y + "? ");
return x * y;
}
public static void displayMessage(boolean isCorrect)
{
if (isCorrect)
System.out.println("Good job! You got it right!");
else
System.out.println("You got it wrong, try again!");
}
public static void main(String[] args)
{
//Scanner to Obtain Input from CW
Scanner input = new Scanner(System.in);
int rightAnswer = 0;
rightAnswer = generateQuestion();
while (input.nextInt() != rightAnswer)
displayMessage(false);
displayMessage(true);
}
}
If I understand your question correctly, It's simply a matter of separating the functionality that prints a question and displays the answer into separate methods. See my edited version of your code below
public class Assign6
{
public static void main(String[] args)
{
// Scanner to Obtain Input from CW
Scanner input = new Scanner(System.in);
// Generate Random Number for Quiz
Random randomNumbers = new Random();
int number1 = 0;
int number2 = 0;
int answer = 0;
// Rolls number from 1-9
number1 = randomNumbers.nextInt(9);
number2 = randomNumbers.nextInt(9);
displayQuestion("How much is " + number1 + " times " + number2 + "?");
answer = input.nextInt();
// If Else While Statements
if (answer == (number1 * number2))
{
displayMessage(Boolean.TRUE);
}
else
{
while (answer != (number1 * number2))
{
displayMessage(Boolean.FALSE);
answer = input.nextInt();
}
}
}
public static void displayQuestion(String q)
{
System.out.println(q);
}
public static void displayMessage(Boolean isCorrect)
{
if (isCorrect)
{
System.out.println("Good job! You got it right!");
}
else
{
System.out.println("You got it wrong, try again!");
}
}
}

Using a scanner input to define the number of scanner inputs required

I have made it a little further. It turns out I can use loops but not arrays in my assignment. So here's the current version (keep in mind no final calculations or anything yet.) So if you look at the homework method, you can see I am asking for the "number of assignments." Now, for each assignment, I need to ask for and sum both the Earned Score and the Maximum Possible Score. So for instance, if there were 3 assignments, they might have earned scores of 18, 22, and 29, and maximum possible scores of 20, 25, and 30 respectively. I need to grab both using the console, but I don't know how to get two variables using the same loop (or in the same method).
Thanks in advance for your help!
import java.util.*;
public class Grades {
public static void main(String[] args) {
welcomeScreen();
weightCalculator();
homework();
}
public static void welcomeScreen() {
System.out.println("This program accepts your homework scores and");
System.out.println("scores from two exams as input and computes");
System.out.println("your grade in the course.");
System.out.println();
}
public static void weightCalculator() {
System.out.println("Homework and Exam 1 weights? ");
Scanner console = new Scanner(System.in);
int a = console.nextInt();
int b = console.nextInt();
int c = 100 - a - b;
System.out.println();
System.out.println("Using weights of " + a + " " + b + " " + c);
}
public static void homework() {
Scanner console = new Scanner(System.in);
System.out.print("Number of assignments? ");
int totalAssignments = console.nextInt();
int sum = 0;
for (int i = 1; i <= totalAssignments; i++) {
System.out.print(" #" + i + "? ");
int next = console.nextInt();
sum += next;
}
System.out.println();
System.out.println("sum = " + sum);
}
}
I don't know where exactly your problem is, so I will try to give you some remarks. This is how I would start (of course there are other ways to implement this):
First of all - create Assignment class to hold all informations in nice, wrapped form:
public class Assignment {
private int pointsEarned;
private int pointsTotal;
public Assignment(int pointsEarned, int pointsTotal) {
this.pointsEarned = pointsEarned;
this.pointsTotal = pointsTotal;
}
...getters, setters...
}
To request number of assignments you can use simply nextInt() method and assign it to some variable:
Scanner sc = new Scanner(System.in);
int numberOfAssignments = sc.nextInt();
Then, use this variable to create some collection of assignments (for example using simple array):
Assignment[] assignments = new Assignment[numberOfAssignments];
Next, you can fill this collection using scanner again:
for(int i = 0; i < numberOfAssignments; i++) {
int pointsEarned = sc.nextInt();
int pointsTotal = sc.nextInt();
assignments[i] = new Assignment(pointsEarned, pointsTotal)
}
So here, you have filled collection of assignments. You can now print it, calculate average etc.
I hope above code gives you some remarks how to implement this.

Java fraction calculator, global variables?

This is my second time asking this question because this assignment is due tomorrow, and I am still unclear how to progress in my code! I am in an AP Computer programming class so I am a complete beginner at this. My goal (so far) is to multiply two fractions. Is there any way to use a variable inside a particular method outside of that method in another method? I hope that wasn't confusing, thank you!!
import java.util.Scanner;
import java.util.StringTokenizer;
public class javatest3 {
static int num1 = 0;
static int num2 = 0;
static int denom1 = 0;
static int denom2 = 0;
public static void main(String[] args){
System.out.println("Enter an expression (or \"quit\"): "); //prompts user for input
intro();
}
public static void intro(){
Scanner input = new Scanner(System.in);
String user= input.nextLine();
while (!user.equals("quit") & input.hasNextLine()){ //processes code when user input does not equal quit
StringTokenizer chunks = new StringTokenizer(user, " "); //parses by white space
String fraction1 = chunks.nextToken(); //first fraction
String operand = chunks.nextToken(); //operator
String fraction2 = chunks.nextToken(); //second fraction
System.out.println("Fraction 1: " + fraction1);
System.out.println("Operation: " + operand);
System.out.println("Fraction 2: " + fraction2);
System.out.println("Enter an expression (or \"quit\"): "); //prompts user for more input
while (user.contains("*")){
parse(fraction1);
parse(fraction2);
System.out.println("hi");
int num = num1 * num2;
int denom = denom1 * denom2;
System.out.println(num + "/" + denom);
user = input.next();
}
}
}
public static void parse(String fraction) {
if (fraction.contains("_")){
StringTokenizer mixed = new StringTokenizer(fraction, "_");
int wholeNumber = Integer.parseInt(mixed.nextToken());
System.out.println(wholeNumber);
String frac = mixed.nextToken();
System.out.println(frac);
StringTokenizer parseFraction = new StringTokenizer(frac, "/"); //parses by forward slash
int num = Integer.parseInt(parseFraction.nextToken());
System.out.println(num);
int denom = Integer.parseInt(parseFraction.nextToken());
System.out.println(denom);
}
else if (!fraction.contains("_") && fraction.contains("/")){
StringTokenizer parseFraction = new StringTokenizer(fraction, "/"); //parses by forward slash
int num = Integer.parseInt(parseFraction.nextToken());
System.out.println(num);
int denom = Integer.parseInt(parseFraction.nextToken());
System.out.println(denom);
}else{
StringTokenizer whiteSpace = new StringTokenizer(fraction, " ");
int num = Integer.parseInt(whiteSpace.nextToken());
System.out.println(num);
}
}}
Is there any way to use a variable inside a particular method outside of that method in another method?
Yes you can do that. You can declare a variable in a method, use it there and pass it to another method, where you might want to use it. Something like this
void test1() {
int var = 1;
System.out.println(var); // using it
test2(var); // calling other method and passing the value of var
}
void test2(int passedVarValue) {
System.out.println(passedVarValue); // using the passed value of the variable
// other stuffs
}

Categories

Resources