I'm confused on what I'm doing wrong here. Anyone care to explain? It compiles and runs but I keep getting an error at line 50 which is the return line.
Also if I change the code below to "int max = (number1, number2) " i get the can not find symbol error. Any help will be greatly appreciated.
int max = max(num1, num2);
import java.io.*;
import java.util.Scanner;
public class MethodLab {
public static void main(String[] args) {
// variable declarations for part 1
String title;
String firstName;
String lastName;
Scanner in = new Scanner(System.in);
// prompt for input for part 1
System.out.print("Enter a title:");
title = in.next();
System.out.print("Enter your first name:");
firstName = in.next();
System.out.print("Enter a your last name:");
lastName = in.next();
// call the method for part 1
greeting(title, firstName, lastName);
// variable declarations for part 2
int number1;
int number2;
// user prompts for part 2
System.out.print("Enter first number:");
number1 = in.nextInt();
System.out.print("Enter second number:");
number2 = in.nextInt();
// call the method for part 2 inside the println statement
System.out.println("The largest number is " + max(number1, number2));
}
/******************** greeting method goes here*********************/
public static void greeting(String proper, String fname, String lname){
System.out.println();
System.out.printf("Dear " + proper +" "+ fname + " "+ lname);
System.out.println();
}
/***********************end of method*************************/
/******************** max method goes here*********************/
public static int max(int num1,int num2){
int max = max(num1, num2);
return max;
}
Use int max = Math.max(num1, num2) this will return the max number.
public static int max(int num1,int num2){
int max = max(num1, num2);
return max;
}
This method would never complete. This is going to call max again and again until you run out of stack space. And when you do, it throws a stack overflow error. You should change it to
public static int max(int num1,int num2){
int max = num1>num2?num1:numb2; // return the highest number.
return max;
}
EDIT: Since you mentioned that you are new to programming, let me add few more detail. If you are in a method A and you call a method B, some amount of space in the stack segment is reserved so that the control knows the line location in method A to resume execution after completing method B. In your case, the max method calls max method again and again. This directly means that more and more space in stack segment gets reserved for each method call. And at some point, it runs out of available space in stack memory and you would end up with such StackOverflow problem.
In general, any method calling itself without modifying the inputs is a red flag in most scenario. This is the case with your max method.
In your max(int num1, int num2) there is no logic, it's just calling itself so will never end:
use like below:
import java.io.*;
import java.util.Scanner;
public class MethodLab {
public static void main(String[] args) {
// variable declarations for part 1
String title;
String firstName;
String lastName;
Scanner in = new Scanner(System.in);
// prompt for input for part 1
System.out.print("Enter a title:");
title = in.next();
System.out.print("Enter your first name:");
firstName = in.next();
System.out.print("Enter a your last name:");
lastName = in.next();
// call the method for part 1
greeting(title, firstName, lastName);
// variable declarations for part 2
int number1;
int number2;
// user prompts for part 2
System.out.print("Enter first number:");
number1 = in.nextInt();
System.out.print("Enter second number:");
number2 = in.nextInt();
// call the method for part 2 inside the println statement
System.out.println("The largest number is " + max(number1, number2));
}
/******************** greeting method goes here*********************/
public static void greeting(String proper, String fname, String lname){
System.out.println();
System.out.printf("Dear " + proper +" "+ fname + " "+ lname);
System.out.println();
}
/***********************end of method*************************/
/******************** max method goes here*********************/
public static int max(int num1,int num2){
return num1 > num2 ? num1 : num2;
}
Related
I'm new to Java. I am tasked with creating a menu program, one option is to generate a username in the form of first initial and surname.
The method is stringOperation(String f, String s)
Variables are fName and sName.
Here is the code. I have highlighted the areas I need help with. The rest of the code is OK, I think. This is a section of the pseudocode that explains what is required:
stringOperation(String f, String s)
3.1.1 Assign first character of first initial to variable using f.substring(start position, length of string).
3.1.2 Concatenate first initial with users surname.
3.1.3 print username to console.
import java.util.Scanner; // imports scanner class
public class Assessment {
public static void main(String[] args) { //main method
menu(); //call menu method
}
public static void menu() { //method to display menu options
int choice;
String fName;
String sName;
Scanner sc = new Scanner(System.in);
//displays menu options
System.out.println("Welcome");
System.out.println("1. Username");
System.out.println("2. Factorial");
System.out.println("3. Area of triangle");
System.out.println("4. Circumference of circle");
System.out.println("5. Exit");
//asks for user input
do {
System.out.println("Enter your first name");
fName = sc.next();
System.out.println("Enter your surname");
sName = sc.next();
System.out.println("Thank you. Now enter a selection (1-5):");
choice = sc.nextInt();
//menu loop
switch (choice) {
case 1:
**stringOperation(String fName, String sName);**
break;
case 2:
numberFactorial();
break;
case 3:
areaTriangle();
break;
case 4:
circumferenceCircle();
break;
}
}while (choice!=5);
}
**//stringOperation method
private static void stringOperation(String f, String s) {
String initial = f.substring(0,1);
String username = initial + s;
System.out.println("Your username is " + initial + s);
}**
public static void numberFactorial() { //method to calculate factorial of a number
//variables
int number;
int factorial = 1;
int i;
//input
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number: ");
number = sc.nextInt();
//for loop
for (i = 1; i <= number; i++) {
factorial = factorial * i;
}
System.out.println("Factorial of " + number + " is " + factorial);
}
public static void areaTriangle ()//method to calculate area of a triangle
{ //input
Scanner sc = new Scanner(System.in);
//variables
double width;
double height;
double area;
//input
System.out.println("Enter the width: ");
width = sc.nextInt();
System.out.println("Enter height: ");
height = sc.nextInt();
area = (height * width) / 2;
System.out.println("The area is :" + area);
}
public static void circumferenceCircle ()//method to calculate circumference of a circle
{ //variables
double radius;
double circumference;
Scanner sc = new Scanner(System.in);
System.out.println("Enter radius: ");
radius = sc.nextDouble();
circumference = Math.PI * 2 * radius;
System.out.println("The circumference is : " + circumference);
}
}
If you want to make the method cleaner you could do something like this
private static void stringOperation(String f, String s) {
System.out.println("Your username is " + f.substring(0,1) + s)
}
If you need to refer back to the new username then have a global variable that your method can set to refer to later like this.
private static void stringOperation(String f, String s) {
Assessment.username = f.substring(0,1) + s;
System.out.println("Your username is " + Assessment.username);
}
I have a Java program that is designed to take an input of customers, then run a loop for each. Then the user has 3 choices to input: clowns, safari sam, or music caravan. I just don't understand what is wrong with my if statements. You see, if a user enters "clowns", the corresponding if statement works fine and the if statement is executed. However, if a user inputs "safari sam" or "music caravan", the if statements do not execute.
My question is: If the first if statement is executed, then why are the other 2 being skipped (not executing when conditions are met)?
CODE:
import java.util.Scanner;
public class FunRentals {
public static void main(String[] args) {
Scanner new_scan = new Scanner(System.in);
System.out.println("Enter the amount of customers: ");
int num_customers = new_scan.nextInt();
for(int i = 1; i<=num_customers; i++){
System.out.println("Please enter the service used (\"Clowns\", \"Safari Sam\", or \"Music Caravan\") for customer #"+i);
String service_type = new_scan.next();
String service_type_real = service_type.toLowerCase();
if(service_type_real.equals("clowns")){
System.out.println("Please enter the amount of ADDITONAL hours");
double additional_hours = new_scan.nextDouble();
System.out.println("The total bill for customer #" +i +" is "+ clowns(additional_hours));
}
else if(service_type_real.equals("safari sam")){
System.out.println("Please enter the amount of ADDITONAL hours");
double additional_hours = new_scan.nextDouble();
System.out.println("The total bill for customer #" +i +" is "+ safari_sam(additional_hours));
}
else if(service_type_real.equals("music caravan")){
System.out.println("Please enter the amount of ADDITONAL hours");
double additional_hours = new_scan.nextDouble();
System.out.println("The total bill for customer #" +i +" is "+ music_caravan(additional_hours));
}
}
}
public static double clowns(double a){
double additional_cost = a*35;
double total_cost = additional_cost + 45;
return total_cost;
}
public static double safari_sam(double a){
double additional_cost = a*45;
double total_cost = additional_cost + 55;
return total_cost;
}
public static double music_caravan(double a){
double additional_cost = a*30;
double total_cost = additional_cost + 40;
return total_cost;
}
}
You need to use nextLine() instead of next() to read user input. nextLine() will read the entire line, but next() will only read the next word.
For reading String provided by the user in console you have to use .nextLine()
So try by using this -
String service_type = new_scan.nextLine();
This should store the value of whatever you are providing in the console to the String "service_type".
I can't get this to run.There is a tester program and a method below. it says error identifier expected.Thanks in advance
public class 121tester{
public static void main(String[]args){
Scanner input= new Scanner(System.in)
System.out.println("Enter first number");
int num1=input.nextInt();
System.out.println("Enter second number");
int num2=input.nextInt();
System.out.println("The Greatest common factor of "+num1+" "+num2+" is "+GCD(num1,num2));
}
}
private static int GCD(int num1, int num2){
if(num2==0){
return num1;
}
return(GCD(num2, num1%num2);
}
Class name can't start with number. Change from
class 121tester
to
class Tester121
Another thing your GCD method should declare into inside class. It is better to use some IDE at initial stage of programming to remove compiler error.
Try the following:
import java.util.Scanner;
public class GCDTester{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter first number");
int num1 = input.nextInt();
System.out.println("Enter second number");
int num2 = input.nextInt();
System.out.println("The greatest common factor of " + num1 + " " + num2 + " is " + gcd(num1,num2));
}
private static int gcd(int num1, int num2){
if (num2 == 0) {
return num1;
}
return gcd(num2, num1 % num2);
}
}
But #Masud is correct, you should place the gcd method in a class of its own so that it can be used as an object in its own right.
when my program gets to the part where it asks for the name of the fruit, it will output the string asking for the name, then immediately go to the next string output without waiting for the user input.
This seems to automatically assign a value of null to my name variable.
Fruit.java
public class Fruit {
String Name;
int Quantity;
double Mass;
public Fruit(String Name, int Quantity, double Mass) {
this.Name = Name;
this.Quantity = Quantity;
this.Mass = Mass;
}
public void Information() {
System.out.println("This fruit is an " + Name + ", there's " + Quantity
+ " of it and it weighs " + Mass + " grams");
}
}
Fruits.java
import java.util.Scanner;
public class Fruits {
public static void main(String[] args) {
Fruit menu[];
int number;
String name;
int quantity;
double mass;
System.out
.print("How many fruits would you like to add to the menu?: ");
Scanner input = new Scanner(System.in);
number = input.nextInt();
input.nextLine();
menu = new Fruit[number];
for (int i = 0; i < menu.length; i++) {
System.out.println("What would you like to name the fruit?: ");
name = input.nextLine();
System.out.println("How much fruits are there?: ");
quantity = input.nextInt();
System.out.println("What is the mass of the Fruit in grams?: ");
mass = input.nextDouble();
menu[i] = new Fruit(name, quantity, mass);
menu[i].Information();
}
input.close();
}
}
instead of input.nextInt(); use Integer.parseInt(input.nextLine()). it might solve your issue.
When you use input.nextInt() there is a %n char in hub. You need to use a input.nextLine() after to remove the line-break charcater. You can also use input.nextLine() for each variables and then parse it yourself.
Warning! In java convention the method name, attribute name and parameter name must begin by an lower case character.
the problem is scanning for ints, then nextLine. When you run .nexInt() I believe there is a newline character not scanned in, so this immediately messes with the following .nextLine(), as it only takes in the newline and nothing after
The easiest fix I am aware of is
number = input.nextInt();
input.nextLine();
menu = new Fruit[number];
And then the rest of the code should work
As an aside, usually you would start the loop from 0, because arrays start from 0, and you will have a blank first entry, but I don't think it matters in this particular piece of code
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
}