When calling scanDouble(); I get an error.
package com.company;
import java.util.Random;
import java.util.Scanner;
public class Main {
Scanner in = new Scanner(System.in);
public static void printLogarithm(double x){
if(x <= 0.0){
System.err.println("Error: x must be positive.");
return;
}
double result=Math.log(x);
System.out.println("The log of x is"+ result);
}
public static void scanDouble(Scanner in) {
System.out.print("Enter the name: ");
if (!in.hasNextDouble()){
String word = in.next();
System.err.println(word + "is not a number");
return;
}
double x = in.nextDouble();
printLogarithm(x);
}
public static void main(String[] args) {
scanDouble();
}
}
Does anyone know how to execute scanDouble(); Is there something I should include in the method call?
If I follow your logic, try passing the Scanner variable in inside the scanDouble() method like this:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
scanDouble(in);
}
Passing a double value x for instance as an argument won't work, I just tested it.
Related
I started learning JAVA a couple of days ago, so my question might be too basic.
I have created a piece of code which is as follows:
import java.util.Scanner;
public class Que01 {
public static void main(String[] args) {
int principle=acceptInt("Principle");
int roi=acceptInt("Rate Of Interest");
int years=acceptInt("Years");
float si=simpleInterest(principle,roi,years);
System.out.println("Simple Interest for given details is : "+si);
}
static int acceptInt(String s1)
{ System.out.println("Please Enter value for "+s1+" :");
Scanner sc = new Scanner(System.in);
int i= sc.nextInt();
return i;
}
static float simpleInterest(int p,int r, int yr)
{
return p*yr*r/100;
}
}
I want to know where should I write:
sc.close();
Also:
Any other suggestion to code for improvement are Welcome!
You should not close the scanner do not worry about that it will terminated after calculating the simpleInterest. When you run the program and after entering required values it will calculate and return the result and quit.
In you code 1 improvement is you should not create Scanner object again and again there should be only 1 object of Scanner throughout the life cycle.
Below is your updated code -
public class Que01 {
private static Scanner sc = null;
public static void main(String[] args) {
sc = new Scanner(System.in);
int principle=acceptInt("Principle");
int roi=acceptInt("Rate Of Interest");
int years=acceptInt("Years");
float si=simpleInterest(principle,roi,years);
System.out.println("Simple Interest for given details is : "+si);
}
static int acceptInt(String s1)
{ System.out.println("Please Enter value for "+s1+" :");
int i= sc.nextInt();
return i;
}
static float simpleInterest(int p,int r, int yr)
{
return p*yr*r/100;
}
}
Create Scanner on start of the program and use it again and again. thats it
hope this will help you.
Thanks to Vince, I was able to create a good version of my code.
and this is the answer I needed.
public class Que01 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int principle=acceptInt(sc,"Principle");
int roi=acceptInt(sc,"Rate Of Interest");
int years=acceptInt(sc,"Years");
sc.close();
float si=simpleInterest(principle,roi,years);
System.out.println("Simple Interest for given details is : "+si);
}
static int acceptInt(Scanner sc,String s1)
{ System.out.println("Please Enter value for "+s1+" :");
int i= sc.nextInt();
return i;
}
static float simpleInterest(int p,int r, int yr)
{
return p*yr*r/100;
}
}```
import java.util.Scanner;
public class Que01 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int principle = acceptInt("Principle", false, sc);
int roi = acceptInt("Rate Of Interest", false, sc)
int years = acceptInt("Years", true, sc);
float si = simpleInterest(principle, roi, years);
System.out.println("Simple Interest for given details is : " + si);
}
static int acceptInt(String s1, boolean closeScanner, Scanner sc) {
System.out.println("Please Enter value for " + s1 + " :");
int i = sc.nextInt();
if (closeScanner)
sc.close();
return i;
}
static float simpleInterest(int p, int r, int yr) {
return p * yr * r / 100;
}
}
i am not sure if this is a good practice of passing boolean as parameter to decide to close scanner
import java.util.Scanner;
public class Que01 {
Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int principle = acceptInt("Principle");
int roi = acceptInt("Rate Of Interest");
int years = acceptInt("Years");
float si = (p * yr * r/100);
System.out.println("Simple Interest for given details is : " + si);
}
static int acceptInt(String s1) {
System.out.println("Please Enter value for " + s1 + " :");
int i = sc.nextInt();
sc.close();
return i;
}
}
This is what I would say but I'm not an expert. sc.close just saves anything you did with the scanner, eg. writing to a file and saving the file. - thus in this scenario I wouldn't even use it. I also wouldn't use a method to calc the si unless you plan to use it elsewhere as it's just taking up more space
I wanna make a condition if somebody input a word the program will return "That is a string" if it is an integer the program will return "That is an integer ". What's wrong with my if condition ?
package folder;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner skaner = new Scanner(System.in);
while (skaner.hasNext()){
if (skaner.next() != int) {
System.out.println("That is a string" + skaner.next());
}
else {
System.out.println("That is an integer " + skaner.next());
}
}
skaner.close();
}
}
Here skaner.next() will return a String object whereas int is a primitive data type and therefore both are not comparable. To check if token returned by skaner.next() is an int or not, you can use Integer.parseInt(skaner.next()) which converts String to int and throws a NumberFormatException if input is not a valid integer.
package folder;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner skaner = new Scanner(System.in);
while (skaner.hasNext()){
String x = skaner.next();
try {
int y = Integer.parseInt(x);
System.out.println("That is an integer " + y);
}
catch(NumberFormatException e) {
System.out.println("That is a string " + x);
}
}
skaner.close();
}
}
Check this link for reference.
package aj;
import java.util.Scanner;
public class ConvertingNumber {
public static void main(String[] args) {
Scanner a = new Scanner(System.in);
System.out.println("Enter the Number");
int num = a.nextInt();
System.out.println("Enter the base for the given number");
int base = a.nextInt();
converting(num,base);
public static int converting(int num , int base) {
String sum="";
while(num > 0) {
int rem = 0;
rem = num % base;
num = num / base;
sum = rem + sum;
}
System.out.println(sum);
}
}
}
for my above java code,am getting compier error saying:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The method converting(int, int) is undefined for the type ConvertingNumber
void is an invalid type for the variable converting
Syntax error on token "(", ; expected
Duplicate local variable num
Syntax error on token ",", ; expected
Duplicate local variable base
Syntax error on token ")", ; expected
at aj.ConvertingNumber.main(ConvertingNumber.java:12)
Please anyone help me out in solving this. Thanks in advance.
converting method should be out side from the main method
package aj;
import java.util.Scanner;
public class ConvertingNumber {
public static void main(String[] args) {
Scanner a=new Scanner(System.in);
System.out.println("Enter the Number");
int num=a.nextInt();
System.out.println("enter the base for the given number");
int base=a.nextInt();
converting(num,base);
}
//This method should be out side the main method
public static void converting(int num , int base) {
String sum="";
while(num>0) {
int rem=0;
rem=num%base;
num=num/base;
sum=rem+sum;
}
System.out.println(sum);
}
}
I have Corrected Your code..
package aj;
import java.util.Scanner;
public class ConvertingNumber {
public static void main(String[] args) {
Scanner a=new Scanner(System.in);
System.out.println("Enter the Number");
int num=a.nextInt();
System.out.println("enter the base for the given number");
int base=a.nextInt();
ConvertingNumber .converting(num,base);
//converting(num,base);
}
public static int converting(int num , int base)
{
int sum=0;
while(num>0)
{
int rem=0;
rem=num%base;
num=num/base;
sum=rem+sum;
}
//System.out.println(sum);
return sum;
}
}
I have a basic quadratic formula program, but I've modified the beginning to end the program if any value other than a double is entered. However, because I've done this, I can't seem to be able to use the value inputted anywhere else in the program. Here are the first few lines:
import java.util.Scanner;
public class QuadraticFormula
{
public static void main(String[] args)
{
double a, b, c;
Scanner reads = new Scanner(System.in);
System.out.println("General equation: \"ax^2 + bx + c\"");
System.out.print("Enter value of \"a\": ");
try {
String doubleString = reads.nextLine();
a = Double.parseDouble(doubleString);
}
catch (Exception e) {
System.out.println("Invalid Data Type. Please enter a number");
}
The rest of the program asks for the values of b and c, and then carries out the quadratic equation, retuning the roots of whatever equation was entered. However, because the value of a is defined inside the try section, the compiler tells me that a hasn't been initialized. How do I fix this?
EDIT: I do want to use the data inputted by the user in the program (stored as doubleString)––but a number. My immediate problem is the compiler error, but is there any way to use the information inputted even though it's inside the try block? Because when I tried to equate double a to double doubleString outside the block it said doubleString didn't exist.
Like #Elliot Frisch said, you can just initialize a to a value (0) and take care that you don't get any wrong values due to failed parsing.
In your case this would probably mean to return/exit the program with the error message.
This is actually a common pattern.
import java.util.Scanner;
public class QuadraticFormula
{
public static void main(String[] args)
{
double a = 0, b, c;
Scanner reads = new Scanner(System.in);
System.out.println("General equation: \"ax^2 + bx + c\"");
System.out.print("Enter value of \"a\": ");
try {
String doubleString = reads.nextLine();
a = Double.parseDouble(doubleString);
}
catch (Exception e) {
System.out.println("Invalid Data Type. Please enter a number");
return;
}
//do work with a
Just initialize a when you declare it :
public static void main(String[] args)
{
double a = 0.0;
double b, c;
Scanner reads = new Scanner(System.in);
The other thing you can do is declare a as a "Class Property" :
public class QuadraticFormula
{
protected static double a = 0.0;
public static void main(String[] args)
{
double b, c;
Scanner reads = new Scanner(System.in);
try {
String doubleString = reads.nextLine();
QuadraticFormula.a = Double.parseDouble(doubleString);
}
catch (Exception e) {
System.out.println("Invalid Data Type. Please enter a number");
}
Please note how the Class property (a) MUST be accessed using a static reference within main() as main() is static, which breaks the Java rule of using getter/setter to access Class properties. One thing I would recommend you should begin to learn how to package Class functionality outside of main()...outside of static references...
import java.util.Scanner;
public class QuadraticFormula {
protected double a = 0.0;
public static void main ( String[] args ) {
QuadraticFormula lnewItem = new QuadraticFormula();
try {
lnewItem.doSomething();
} catch ( Exception e ) {
e.printStackTrace();
}
}
public void doSomething () throws Exception {
double b, c;
Scanner reads = new Scanner(System.in);
System.out.println("General equation: \"ax^2 + bx + c\"");
System.out.print("Enter value of \"a\": ");
try {
String doubleString = reads.nextLine();
setA ( Double.parseDouble(doubleString) );
System.out.println("setA() - [" + getA() + "]");
}
catch (Exception e) {
System.out.println("Invalid Data Type. Please enter a number");
}
}
public double getA () {
return a;
}
public void setA ( double a ) {
this.a = a;
}
}
Please note in the last section of code, all the static references are removed other than main(). New getter/setter methods are in place for the Class property a, thus enforcing Java's data encapsulation.
There are two fixes for this, one is to simply return from your main method when an exception is throw like so:
double a;
Scanner reads = new Scanner(System.in);
System.out.println("General equation: \"ax^2 + bx + c\"");
System.out.print("Enter value of \"a\": ");
try {
String doubleString = reads.nextLine();
a = Double.parseDouble(doubleString);
}
catch (Exception e) {
System.out.println("Invalid Data Type. Please enter a number");
return;
}
The other option stated by others is giving 'a' an initial value. I would suggest initializing it as NaN (Not a Number) and then checking it has been properly initialized before using it like so:
double a = Double.NaN;
Scanner reads = new Scanner(System.in);
System.out.println("General equation: \"ax^2 + bx + c\"");
System.out.print("Enter value of \"a\": ");
try {
String doubleString = reads.nextLine();
a = Double.parseDouble(doubleString);
}
catch (Exception e) {
System.out.println("Invalid Data Type. Please enter a number");
}
if(Double.isNaN(a)){
System.out.println("Variable 'a' is invalid, please enter a valid number.");
}
else {
double result = 2 * a;
}
instead of this line:
double a, b, c;
just replace it with this:
double a=0, b, c;
Currently I am writing a program for an introductory Java class. I have two pieces to my puzzle. Hopefully this is a relatively simple to answer question.
Firstly, here is what I am trying to use as my main program:
import java.util.Scanner;
public class TheATMGame
{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
double newBalance = 0;
double monthlyInterest = 0;
int answer = 0;
int i=1;
while (i < 100) {
System.out.print ("Please enter your ID: ");
answer = input.nextInt();
System.out.println(" ");
if (answer >=0 && answer<10)
TheATMGame.runGame (answer);
else
System.out.println("Sorry, this ID is invalid.");
}
}
public static void runGame(int id) {
double amount = 0;
int continueOn = 0;
while (continueOn < 4) {
ATMGame myATM = new ATMGame();
Scanner input = new Scanner(System.in);
System.out.println ("---Main menu--- ");
System.out.println ("1: Check balance ");
System.out.println ("2: Withdraw ");
System.out.println ("3: Deposit ");
System.out.println ("4: exit ");
int answer = input.nextInt();
if (answer == 1)
System.out.println("your balance is: " + myATM.getBalance (id));
else if (answer == 2){
System.out.println("Enter an amount to withdraw: ");
amount = input.nextInt();
myATM.withdraw(amount, id);
}
else if (answer == 3)
{
System.out.println("Enter an amount to deposit: ");
amount = input.nextInt();
myATM.deposit(amount, id);
}
else if (answer == 4)
continueOn = 4;
else if (answer > 4)
System.out.println ("Please review the main menu. " +
"Your selection must be between 1-4.");
}
}
//ATM class (balance, annualInterestRate2, id2)
//ATM myATM = new ATM (20000, 4.5, 1122 );
//newBalance = myATM.withdraw(2500);
//newBalance = myATM.deposit(3000);
//monthlyInterest = myATM.getMonthlyInterestRate();
//System.out.println("Your current balance is: " + newBalance);
//System.out.println ("Your monthly interest rate is: " + monthlyInterest);
}
Now here are all of the classes I want to impliment into that program:
import java.util.Date;
public class ATMGame {
private double annualInterestRate = 0;
private double balance = 0;
private int id = 11;
private int[] ids = {0,1,2,3,4,5,6,7,8,9};
private int[] balances = {100,100,100,100,100,100,100,100,100,100};
public Date dateCreated;
public ATMGame() {
}
public ATMGame (double balance2, double annualInterestRate2, int id2) {
balance = balance2;
annualInterestRate = annualInterestRate2;
id = id2;
dateCreated.getTime();
}
public double getMonthlyInterestRate() {
double monthlyInterest = annualInterestRate/12;
return monthlyInterest;
}
public double withdraw(double amountWithdrawn, int id) { //This method withdraws money from the account
double newBalance = balances[id] - amountWithdrawn;
System.out.println("Your withdrawel has processed. New balance: " + newBalance);
balances[id] = (int) newBalance;
return newBalance ;
}
public double deposit(double amountDeposited, int id) { //This method deposits money in the account
double newBalance = balances[id] + amountDeposited;
System.out.println("Your deposit has processed. New Balance is: " + newBalance);
balances[id] = (int) newBalance;
return newBalance ;
}
public double getBalance(int id) {
double myBalance = balances[id];
balance = myBalance;
return myBalance ;
}
}
When I try to run the first program it says "No Main classes found."
As you can see I have written the line " public void Main() ..." to take care of this, but eveidently it does not work. What am I doing wrong?
Replacing "public void Main() {" with "public static void main(String[] args) {" still returns the error: "No Main classes found." :/
http://img21.imageshack.us/img21/9016/asdfsdfasdfg.jpg
I was able to fix it by changing Main.java to TheATMGame.java and then running from ATMGame.java.
You should use:
public static void main(String[] args)
Instead of Main because the JVM calls this method first. It is a convention.
You've just misdefined main. Should be:
public static void main(String[] args) {
....
}
You're going to run into some other problems with your code, though. From a quick glance...
Your main() is a function, as well as runGame() - one shouldn't be defined within the other.
You cannot name your two classes the same thing - call the main() class something different than ATMGame.
Not sure where you're going with ATM class (balance, annualInterestRate2, id2), but it's not valid Java.
Your method signature must be:
public static void main(String[] args) {
...
}
That's the convention you have to follow. Anything else won't work.
In your class ATMGame, replace the following:
public void Main() {
with:
public static void main(String[] args) {
Additionally, since this method has to be static, you'll need to change the following:
if (answer >=0 && answer<10)
runGame (answer);
else
with:
if (answer >=0 && answer<10)
ATMGame.runGame (answer);
else
Then finally, you need to change the method signature of rungame to also be static. Change it from:
public void runGame(int id) {
to:
public static void runGame(int id) {
The names of your public classes should match the file names. This is not the case in your screenshot. Also make sure that everything compiles correctly and then retry (using a public static void main(String[] args) { ... } method).