I'm trying to write a program that compares a double (entered by the user) to the constant Math.PI, after having converted both values to Strings and then comparing them char by char. I'm getting errors but I'm not able to see where I should change my code. Any tips/help is greatly appreciated!
import java.util.Scanner;
public class Main {
private static int matches = 0;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter value to compare");
double compare = scan.nextDouble();
compare(compare);
}
public static int compare(double value){
String input = String.valueOf(value);
String original = String.valueOf(3.523);
//String.valueOf(Math.PI);
if(input.charAt(0) == 3){
for(int i = 3; i <= input.length(); i++){
if(input.charAt(i) == (original.charAt(i))){
matches++;
}
}
return matches;
} else
return matches;
}
}
Your question is not clear
What is concretely the expected behavior here?
I can't manage to understand your thought process in the compare method.
If you wan't to compare a double with Math.PI, it is easy as double are primitive variables, you can use the "==" operator, just do:
if (scannedValue == Math.PI)
System.out.println ("values are equals");
And for the runtime exception that you have it is because you did not pass a correct double variable to your scanner.
https://docs.oracle.com/javase/7/docs/api/java/util/InputMismatchException.html
Related
Please help I cannot run this block of code:
import java.util.Scanner;
public class Methods_in_java {
public static void main(String[] args) {
boolean gameover = true;
int score = 5000;
int Levelcomplete = 5;
int bonus = 100;
boolean prize = true;
System.out.println("Please enter your name");
Scanner lic = new Scanner(System.in);
String ab = lic.nextLine();
char fir = Character.toUpperCase(ab.charAt(1));
if(fir == 'A'){
prize = true;
}
Calculatescore(gameover,score,Levelcomplete,bonus,prize);
}
public static void Calculatescore(boolean gameover,int score,int levelcomplete,int bonus,boolean prize){
if(gameover){
int finalscore = score + (levelcomplete * bonus);
if (prize){
finalscore += 1000;
}
System.out.println("Your final score is "+ finalscore);
}
}
}
charAt is zero based.
You should use ab.charAt(0) if you use only a single char.
Another good advice is to start method names with a lower case and use the camelCase format.
String ab = lic.nextLine();
char fir = Character.toUpperCase(ab.charAt(1));
Is fir supposed to be the first character in the user String? In that case you want to make sure to take zero-based indexing into account:
char fir = Character.toUpperCase(ab.charAt(0));
You have initialized your prize variable as true that will remain always true even its meet if condition or not just change it to false.
and as you were accessing the String's 2nd character using charAt(1), the index starts from 0 and if you try using charAt(0) then you will access 1st character.
Just change your code to:
public class cn {
public static void main(String[] args) {
boolean gameover = true;
int score = 5000;
int Levelcomplete = 5;
int bonus = 100;
boolean prize=false;
System.out.println("Please enter your name");
Scanner lic = new Scanner(System.in);
String ab = lic.nextLine();
char fir = Character.toUpperCase(ab.charAt(0));
if(fir == 'A'){
prize = true;
}
Calculatescore(gameover,score,Levelcomplete,bonus,prize);
}
public static void Calculatescore(boolean gameover,int score,int levelcomplete,int bonus,boolean prize){
if(gameover){
int finalscore = score + (levelcomplete * bonus);
if (prize){
finalscore += 1000;
}
System.out.println("Your final score is "+ finalscore);
}
}
}
It would be helpful if you elaborated more on what your problem is,
do you have a run time error, a compile time error, or it the output just not what you'd expect.
Your problem may be that arrays start at 0 so the first letter is charAt(0).
Actually I believe another user mentioned that the prize variable was initialized to true. I believe that that is the issue and that answer should be marked correct.
Basically I am trying to use a scanner as a method. This is what I have (I've used int in the meantime because I have not been able to figure out how to use Scanner as a parameter)
public class LoopPatterns {
public static int sum(int number1, int number2){
int sum = number1 + number2;
return sum;
}
public static void main(String[] args) {
System.out.println(sum(3, 4));
}
}
So this is what I have so far. However, the main point is that I need to get the sum of an unspecified amount of digits. I need to use a scanner but I haven't been able to figure out how to use it as a parameter of my method. Anyway, I hope that was concise enough. Thanks!
Just set the method so it accepts a reference of the scanner instead of pre-written ints.
public static int sum(Scanner myScanner){
int sum = 0;
String line;
while((line = myScanner.nextLine()) != "")
sum += Integer.parseInt(line);
return sum;
}
This method will accept a scanner as a parameter and then keep inputting numbers into the sum until the user inputs a blank character.
I wrote some code pertaining to the problem but I just can't get it to work. After I input the two numbers, the program gets stuck in an infinite loop. Is there any way this method could work or is it outright wrong?
import java.util.Scanner;
public class Arithmetic {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter the numerator and denominator respectively : ");
double a = input.nextDouble();
double b = input.nextDouble();
double c;
for(c=0;;c+=0.000000000001){
if(b*c==a){
break;
}
}
System.out.print(c);
}
}
I can think of one way without a slash:
double c = a * Math.pow(b, -1);
You can also substitute a Unicode escape for the / character.
double c2 = a \u002f b;
You can also convert to BigDecimals, use the divide method, and then convert the quotient back to a double.
double c3 = new BigDecimal(a).divide(new BigDecimal(b)).doubleValue();
You can use exponent and logarithm becasue exp(log(a)-log(b)) =a/b
public class HelloWorld{
public static void main(String []args){
System.out.println(Math.pow(10,Math.log10(a)-Math.log10(b)));
}
}
You need to add checks for a>0 and b>0 and make logic so it work for all a,b but this you can do yourself.
For example if b = 0
Throw error
if a<0 and b>0
System.out.println(-Math.pow(10,Math.log10(-a)-Math.log10(b)));
etc.
System.out.println("The result is : " + (a * Math.pow(b, -1)));
public class Num {
public static void main(String[] args) {
double num, den, res;
num = 10;
den = 2;
res = Math.pow(Math.E, (Math.log(num)-Math.log(den)));
System.out.println(res);
}
}
I'm currently modifying a previous Java program that computes quadratic formula type math problems by breaking parts of my code down into methods and calling those methods to complete the same task. Currently I'm stuck on creating a method to calculate the discriminant in the numerator. As assigned, I'm supposed to have one method that receives user input for the a,b, and c values, but I'm not sure how to get those values from one method into the next that is supposed to use those values in calculations.
My instructor wants us to have the a b and c variables input into an array and I know the way it is now is a pretty manual way of putting values into an array, but should still work for this purpose.
Here is what I have thus far and thanks for reading.
EDIT: I've started again from scratch, I can't figure out how to properly return information from my methods so that the next can use it. I keep getting method argument not applicable errors. Any ideas?
import java.util.*;
public class QuadraticMethods {
public static void main(String[] args){
getValues();
calcDisc(userInput);
}
public static double[] getValues() {
double[] userInput;
userInput = new double[3];
Scanner kbd = new Scanner(System.in);
System.out.println("Fourth Assignment by MyNameHere");
System.out.println("Welcome to the quadratic formula computation tool.");
System.out.println("This tool will solve problems in the form of: a^x + bx + c.");
System.out.println("Please enter the values you would like for a, b, and c.");
for (int i = 0; i < userInput.length; i++) {
userInput[i] = kbd.nextDouble(); }
double aValue = userInput[0];
double bValue = userInput[1];
double cValue = userInput[2];
/*
System.out.println(aValue);
System.out.println(bValue);
System.out.println(cValue);
*/
return userInput;
}
public static double calcDisc(double[] userInput) {
double aValue = userInput[0];
double bValue = userInput[1];
double cValue = userInput[2];
double radicalValue = (Math.pow(bValue, 2) - (4*aValue*cValue));
System.out.println(radicalValue);
return radicalValue;
}
}
To get your current code to work, only a small change is required:
public static void main(String[] args) {
double[] userInput = getValues();
calcDisc(userInput);
}
Further these assignments are not actually used.
public static double[] getValues() {
// ...
double aValue = userInput[0];
double bValue = userInput[1];
double cValue = userInput[2];
// ...
}
Some other improvements could be:
The result should not be printed by the method that calculates it. You already declared the method the right way by returning the value. Now you should use the returned value and print the result in the calling method.
public static void main(String[] args) {
double[] userInput = getValues();
double radicalValue = calcDisc(userInput);
System.out.println(radicalValue);
}
// ...
public static double calcDisc(double[] userInput) {
double aValue = userInput[0];
double bValue = userInput[1];
double cValue = userInput[2];
double radicalValue = (Math.pow(bValue, 2) - (4 * aValue * cValue));
return radicalValue;
}
Printing the banner should probably not be mixed with requesting the user input. Imagine, you would want to repeat the read/evaluate/print cycle:
public static void main(String[] args) {
while (true) {
double[] userInput = getValues();
double radicalValue = calcDisc(userInput);
System.out.println(radicalValue);
}
}
would print the banner text every time. Isolating the responsibilities enables you to alter behaviour without affecting unrelated code.
public static void main(String[] args) {
printBanner();
while (true) {
double[] userInput = getValues();
double radicalValue = calcDisc(userInput);
System.out.println(radicalValue);
}
}
private static void printBanner() {
System.out.println("Fourth Assignment by MyNameHere");
System.out.println("Welcome to the quadratic formula computation tool.");
System.out.println("This tool will solve problems in the form of: a^x + bx + c.");
}
Scanner should be closed after use. Java 7 try with resources will do that for you.
public static double[] getValues() {
double[] userInput;
userInput = new double[3];
try (Scanner kbd = new Scanner(System.in)) {
System.out.println("Please enter the values you would like for a, b, and c.");
for (int i = 0; i < userInput.length; i++) {
userInput[i] = kbd.nextDouble();
}
}
return userInput;
}
I am using a scanner class to average numbers together. I am using a method to do the averaging. I do not want the program to run if there are more than 20 args. I cant seem to get this to work. I am very new at java and trying to learn.
I appreciate any help I can get. Thanks!
import java.util.Scanner;
class programTwo {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
double x = 0.00d;
if (args != null) {
System.out.println ("Enter your numbers to be averaged. Remember no more than 20!:");
x = scan.nextInt();
if (x <= 21) {
System.out.println("Please do not add more than 20 numbers");
}
} else {
}
}
public double average(double [] values) {
double average = 0.0;
if ((values != null) && (values.length > 0)) {
for (double value : values) {
average += value;
}
average /= values.length;
}
return average;
}
}
Just run a while loop that breaks when 20 "args" is met or until a break like -1 is entered. Then if you are taking double values, you should use x = scan.nextDouble(). You also do not have a place where you are inserting the values into your array. At the end of your while loop you could put x into an array of doubles.
private double x;
private double Foo[] = new Foo[20];
private int this = 0; //Your counter
while(this < 20 && x != -1)
{
x = scan.nextDouble();
Foo[this++] = x;
}
Then carry out your public double Average by adding up the values in the array and dividing by (double)this
Here is a solution (cleaning up a lot of your code as well) that gets all the numbers on one line after the start of the program:
import java.util.Scanner;
class programTwo {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
double values[] = new double[20];
int count = 0;
System.out.println ("Enter your numbers to be averaged. Remember no more than 20!:");
String inputs = scan.nextLine();
scan = new Scanner(inputs); // create a new scanner out of our single line of input
while(scan.hasNextDouble())
{
if(count == 20)
{
System.out.println("You entered too many numbers! Fail.");
return;
}
values[count] = scan.nextDouble();
count += 1;
}
System.out.println("Your average is: " + average(values, count));
}
public static double average(double [] values, int count) {
double average = 0.0;
for (double value : values) {
average += value;
}
average /= count;
return average;
}
}
I got thinking you might want to use the args that are passed to main, since you use a null check, so you want to run your program like this:
java programTwo num1 num2 num3 num4 num5
etc. If that's the case, we have another solution:
class programTwo {
public static void main (String[] args) {
if(args.length > 20)
{
System.out.println("You entered too many numbers! Fail.");
return;
}
double values[] = new double[args.length];
for(int i=0; i< args.length; ++i)
values[i] = Double.valueOf(args[i]);
System.out.println("Your average is: " + average(values));
}
public static double average(double [] values) {
double average = 0.0;
for (double value : values) {
average += value;
}
average /= values.length;
return average;
}
}
The args != null check is unnecessary. One way to accomplish what you want is to accept numbers while the scanner has a next number (scanner.hasNext() perhaps) and break if the number of inputs thus far is less than 20. Since the number of double numbers is unknown, you're better off using an ArrayList.
List<Double> doubles = new ArrayList<Double>();
and calling the add method on doubles
doubles.add(x);
Then pass this to a method that averages the values in the arraylist.