Good Evening All,
I need help writing a class that enables to write a code like:
int number = Utility.getInt("Enter an int", '>');
to replace something like:
System.out.println("Enter an int>");
Scanner scan = new Scanner(system.in);
int number = scan.nextInt();
Please find my solution below. I am not sure if I am understanding the prompt correctly, not sure if I need to use a Java pre-defined Utility class or if I just need to name the class Utility. Any help or tip would be greatly appreciated thanks!
public class Utility {
private int number;
public Auto setInt (int number){
return "Enter an int" + number;
if (number>0)
this.number = newNumber;
return this;
}
public int getInt(){
return newNumber;
}
}
Have you tried static methods like below ?
public class Utility {
public static Integer getInt(String message){
System.out.println(message);
Scanner scan = new Scanner(System.in);
Integer number = scan.nextInt();
return number;
}
}
Related
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 4 months ago.
Improve this question
import java.util.Scanner; // Needed to make Scanner available
public static int age()
{
int age;
Scanner scanner = new Scanner(System.in);
System.out.println("How old are you? ");
age = Integer.parseInt(scanner.nextLine());
return age;
}
age();
public static void yesornodisability()
{
String disabled;
Scanner scanner = new Scanner(System.in);
System.out.println("Are you registered disabled(Yes / No)? ");
disabled = scanner.nextLine();
return;
}
yesornodisability();
public static int total()
{
int total;
total = 10;
return total;
}
total();
public static void swimmingprice()
{
if (age()<=18);{
total() = total()/2};
else if (age()>=65);{
total()=total()-3};
else if (yesornodisability().equals("Yes");{
total() = total()-4};
System.out.println("The swimming price for you is "+total()+" pounds.");
}
I am asking two sets of questions the first question is asking there age, second question is asking if they are registered disabled. Then using both results I put them in a if statement. As if they are younger than 18 they get 50% discount, if they are registered disable they get 4 pounds discount. My inputs are working, but when I put them in the if statement they are class it expected and else without if error.
First problem, don't write these isolated statements in the class body yesornodisability();, age(); and total(); . I doubt they compile.
Second store intermediate values. Since age() asks to input the age each time, it will be very inconvenient. Plus the user might enter different values.
int userAge = age();
int totalCost = total();
boolean disability = yesornodisability();
I also made a variable for total() because you want to update the value, and a variable yesornodisability() so the question gets asked immediately.
Your if statements have valid but incorrect syntax. You need to remove the semi-colons after them otherwise they won't have a body and the statement following will always be executed.
Consider calling your methods from within the main method and utilizing the BigDecimal class:
import java.math.BigDecimal;
import java.util.Scanner;
public class AnonymosDaAnimeViewersSwimmingPriceCalculator {
private static final int MAX_YOUTH_AGE = 18;
private static final int MIN_SENIOR_CITIZEN_AGE = 65;
private static final BigDecimal BASE_SWIMMING_PRICE = BigDecimal.TEN; // ₤10.
private static final BigDecimal YOUTH_DISCOUNT_PERCENT = BigDecimal.valueOf(0.5); // 50%.
private static final BigDecimal SENIOR_CITIZEN_DISCOUNT_POUNDS = BigDecimal.valueOf(3); // ₤3.
private static final BigDecimal DISABLED_DISCOUNT_POUNDS = BigDecimal.valueOf(4); // ₤4.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int age = getPositiveIntegerInput("How old are you? ", scanner);
boolean isDisabled = getYesOrNoInput("Are you registered disabled (Yes/No)? ", scanner);
BigDecimal actualSwimmingPrice = getSwimmingPrice(age, isDisabled);
System.out.printf("The swimming price for you is ₤%.2f pounds.%n", actualSwimmingPrice);
}
public static BigDecimal getSwimmingPrice(int age, boolean isDisabled) {
BigDecimal actualSwimmingPrice = BASE_SWIMMING_PRICE;
if (age <= MAX_YOUTH_AGE) {
actualSwimmingPrice = actualSwimmingPrice.multiply(YOUTH_DISCOUNT_PERCENT);
} else if (age >= MIN_SENIOR_CITIZEN_AGE) {
actualSwimmingPrice = actualSwimmingPrice.subtract(SENIOR_CITIZEN_DISCOUNT_POUNDS);
}
if (isDisabled) {
actualSwimmingPrice = actualSwimmingPrice.subtract(DISABLED_DISCOUNT_POUNDS);
}
return actualSwimmingPrice;
}
public static int getIntegerInput(String prompt, Scanner scanner) {
System.out.print(prompt);
int validInteger = -1;
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
validInteger = scanner.nextInt();
break;
} else {
System.out.println("Error: Invalid input, must be integer, try again...");
System.out.print(prompt);
scanner.next();
}
}
return validInteger;
}
public static int getPositiveIntegerInput(String prompt, Scanner scanner) {
int validInteger = getIntegerInput(prompt, scanner);
while (validInteger <= 0) {
System.out.println("Error: Integer must be positive.");
validInteger = getIntegerInput(prompt, scanner);
}
return validInteger;
}
public static boolean getYesOrNoInput(String prompt, Scanner scanner) {
System.out.print(prompt);
String input = scanner.nextLine().toLowerCase();
while (!input.equals("yes") && !input.equals("no")) {
input = scanner.nextLine().toLowerCase();
}
return input.equals("yes");
}
}
Example Usage 1:
How old are you? 25
Are you registered disabled (Yes/No)? No
The swimming price for you is ₤10.00 pounds.
Example Usage 2:
How old are you? 18
Are you registered disabled (Yes/No)? Yes
The swimming price for you is ₤1.00 pounds.
Example Usage 3:
How old are you? 67
Are you registered disabled (Yes/No)? YeS
The swimming price for you is ₤3.00 pounds.
I'm struggling with passing a variable value that a user has entered into my program into a method. I think the technical word is parameters.
The problem I'm having is that after the user enters a number in the getnum() method I want the number to be passed down to the two methods calculation and `calculation_two. However, I can't seem to be able to achieve it.
Just to explain the program, the user enters a number in the getnum() method, then they go to the option method and after they select what option, in the calculations methods the number that was written in the getnum() method needs to be passed down the the calculations methods. Therefore, I will then be able to perform calculations with it that way. I need the program to be set up like this as well for my own personal reasons.
Can anyone assist please?
Thanks
public static void main (String[]args){
getnum();
}
public static void getnum() {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
int num = input.nextInt();
option();
}
public static void option() {
Scanner input2 = new Scanner(System.in);
System.out.println("would you like to see option 1 or 2");
int num2 = input2.nextInt();
if(num2==1) {calculation();}
else if(num2==2) {calculation_two();}
else {System.exit(0);}
}
public static void calculation() {
}
public static void calculation_two() {
}
Please see call by reference and call by value to further clarify how primitives or objects are passed from one method to another.
Here are the steps to pass the parameter from one method to another:
You pass the int you got from the scanner as an argument in the option method call:
public static void getnum() {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
int num = input.nextInt();
option(num); // You pass the int as an argument
}
Now, since you are now calling a method with arguments you need to change the signature of the option method to take a parameter. You pass the int value(theNumber variable) from the option method's parameter to the calculation method call.
Arguments and parameters are terms which are used interchangeably but you can check the difference here.
public static void option(int theNumber) { // option now takes a int parameter
Scanner input2 = new Scanner(System.in);
System.out.println("would you like to see option 1 or 2");
int num2 = input2.nextInt();
if(num2==1) {
calculation(theNumber); // method now takes an argument
}
else if(num2==2) {
calculation_two(theNumber); // method now takes an argument
}
else {System.exit(0);}
}
You pass the parameter again to the calculation(s) method and change the signature to:
public static void calculation(int theNumber) { // method with parameter
}
public static void calculation_two(int theNumber) {
}
Declare your methods to use parameters and return values. Easiest way to do it:
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number: ");
int num = input.nextInt();
System.out.println("would you like to see option 1 or 2");
int option = input.nextInt();
int result = 0;
if (option == 1) {
result = calculation(num);
} else if (option == 2) {
result = calculation_two(num)
} else {
System.out.println("Invalid option, exiting...");
System.exit(0);
}
System.out.println("Result = " + result);
}
private static int calculation(int num) {
// implement this
return 0;
}
private static int calculation_two(int num) {
// implement that
return 0;
}
To answer with secure coding practices
package in.faridabad.mandheer;
public class Main{
public static void main (String[]args){
Main m = new Main();
// Assuming calculation is "sum"
System.out.println("sum is + "+ m.option());
}
private int getnum() {
Scanner input = new Scanner(System.in);
return input.nextInt();
}
int option() {
System.out.println("would you like to see option 1 or 2");
int num2 = getnum();
if(num2==1) {return calculation();}
else if(num2==2) {return calculation_two();}
else {System.exit(0);}
}
private int calculation() {
System.out.println("Enter a number: ");
int num1 = getnum();
return num1;
}
private int calculation_two() {
System.out.println("Enter a number: ");
int num1 = getnum();
System.out.println("Enter 2nd number: ");
int num2 = getnum();
return num1+num2;
}
}
So I'm learning Java in class and I'm really loving it so far but its really hard to understand sometimes. Right now I'm trying to understand how methods work. My question is why my code is not working. I am trying to read in an integer from user input then square it.
Here is my code:
package freetime;
import java.util.Scanner;
public class methods {
public static void main(String []args){
Scanner input = new Scanner(System.in);
System.out.println( " enter a number ");
int number = input.nextInt();
square(number);
}
public static int square(int number){
int num;
num = number * number;
return (num);
}
}
Let's say I input 5 on the console, the program immediately terminates and I cannot figure out why.
As mentioned by others, you don't print the value and the console will close as soon as the program ends. So you could try something like this
public class ScannerTest {
public static void main(String []args){
while(true){
Scanner input = new Scanner(System.in);
System.out.println( " enter a number (-1 to stop)");
int number = input.nextInt();
if(number == -1){
break;
}
int output = square(number);
System.out.println(output);
}
}
public static int square(int number){
int num;
num = number * number;
return (num);
}
}
This will print the result and loop ask for new input as long as you don't stop the program.
In Java, when main method comes to end and if there aren't any non-deamon threads running, the JVM ends. Your program came to an end without printing out the result of the square() call.
/*here is your solution :*/
import java.util.*;
import java.lang.*;
import java.io.*;
/*in java everything has to be in a class */
class SquareNumber
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner input = new Scanner(System.in);
System.out.println( " enter a number ");
int number = input.nextInt();
System.out.println(square(number));
/*something to print the squared number*/
}
public static int square(int number){
int num;
num = number * number;
return (num);
}
}
Your program is terminated because there is no other statement after square(number); statement. So your program executes square(...) method and after then it found end of main function so the program is terminated. To see some output you must print result of square(...) method.
package freetime;
import java.util.Scanner;
public class methods {
public static void main(String []args){
Scanner input = new Scanner(System.in);
System.out.println( " enter a number ");
int number = input.nextInt();
int result=square(number);//executing square(...) method and store the returned value of square method to result variable
System.out.println("Square of "+number+" is : "+ result);//printing result
}
public static int square(int number){
int num;
num = number * number;
return (num);
}
}
Maybe my google-fu is just terrible, but I'm having a very hard time figuring out how to do this. I'm trying to get a scanner to read a string, add the inputs, and return a value. I feel like I am just missing something... for example, I'm not sure how to get a variable set to the first double in the scanner.
import java.util.Scanner;
public class adding {
public static double sum(Scanner input){
Scanner s=new Scanner (System.in);
double i = (s.nextDouble());
double sumAnswer = 0;
while (s.hasNext()){
sumAnswer = sumAnswer + i;
i = s.nextDouble();
}
return sumAnswer;
}
public static void main(String[] args){
System.out.println(sum(new Scanner("1.2 2.8 3.9")));
}
}
You don't really need an i variable.
And, as already mentioned, don't have 2 Scanner's.
public static double sum(Scanner input){
double sumAnswer = 0;
while (input.hasNext()){
sumAnswer += input.nextDouble();
}
return sumAnswer;
}
You shouldn't be resetting the scanner after passing the input.
public class adding {
public static double sum(Scanner input){
double i = (input.nextDouble());
double sumAnswer = 0;
while (input.hasNext()){
sumAnswer = sumAnswer + i;
i = input.nextDouble();
}
return sumAnswer;
}
That ought to work better for you, maybe. I could also be mixing something up there...
I am very new to java and have searched around and can't seem to find what to do. I need to take int number and be able to use it in another method. I have to use two methods to do this. I am unsure how to call upon it.
public static void first()
{
System.out.print("Enter number: ")
Scanner scan = new Scanner(System.in);
int number = scan.nextInt();
}
public static void getNumber(String name, int move)
{
if (number == 1)
{
System.out.println("Player shows one" );
}
Make a method which return a number and call it from another method.
public static int first()
{
System.out.print("Enter number: ")
Scanner scan = new Scanner(System.in);
int number = scan.nextInt();
return number;
}
public static void getNumber(String name, int move)
{
int number = first(); //Call method here.
if (number == 1)
{
System.out.println("Player shows one" );
}
}
Define number as a class attribute.
Something like (its not final/working code)
class myClass{
int number = 3; // Or any other default value
public static void first()
{
//....
obj.number = scan.nextInt();
//...
}
public static void getNumber(String name, int move)
{
if (obj.number == 1)
{
//......
}
}
}
After int number call method
int number = scan.nextInt();
getNumber("Your Name", number);