Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
So I wrote this program but for some reason my else statement won't work.
If i input "e" for example my program will simply crash... when its actually supposed to return "Invalid Input"
Can someone please help me?
=========================================================================
import java.util.Scanner;
public class AbsValue2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number:");
String num = input.nextLine();
Double num2 = new Double(Double.parseDouble(num));
Double abs_val = new Double(Math.sqrt(num2 * num2));
if (num.matches("[+-]?[\\d]+[.]*"))
System.out.println("The absolute value of " + num + " is |" + abs_val + "|");
else if (num.matches("[+-]?[\\d]*.[\\d]+"))
System.out.println("The absolute value of " + num + " is |" + abs_val + "|");
else
System.out.println("Invalid input");
}
}
the problem is here:
Double num2 = new Double(Double.parseDouble(num));
if num is "e", then you will get a NumberFormatException.
You can use Scanner.hasNextDouble{}, to check, or try/catch that exception.
Your code is throwing a NumberFormatException before the if statement is reached, because of this line:
Double num2 = new Double(Double.parseDouble(num));
You need to check the validity before parsing it.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Using the following code I am looking the highest number of the variable,The Nested else if statement, not printing please help what is the reason this code is not executed
import java.util.Scanner;
public class Nestedifelese {
static int A;
static int B;
static int C;
public static void main(String[] args) {
Scanner obj= new Scanner(System.in);
System.out.println("Enter the A object number :");
A=obj.nextInt();
System.out.println("Enter the B object number :");
B=obj.nextInt();
System.out.println("Enter the C object number :");
C=obj.nextInt();
System.out.println("The value of A is"+ A);
System.out.println("The value of B is"+ B);
System.out.println("The value of C is"+ C);
if(A>=B)
{
if (A>=C)
{
System.out.println("The Higgest number is" +A);
}
}
else if (B>=A)
{
if (B>=C)
{
System.out.println("The Higgest number is" +B);
}
}
else if (C>=A)
{
if (C>=B)
{
System.out.println("The Higgest number is" +C);
}
}
}
}
At least one of A>=B and B>=Awill be true so it never reaches else if (C>=A). If you want to use if-else instead of the Math.max function, change the else if to if should resolve the problem.
Your problem is in if conditions. Your second condition B>=A is exact opposite of first condition A>=B. So if first condition will be false then second condition will always be true and it will never reach to third condition.
You should use Math.max to filter our highest number of else you can change your if conditions like this:
if(A>=B && A>=C) {
System.out.println("The Higgest number is" +A);
}
if (B>=A && B>=C) {
System.out.println("The Higgest number is" +B);
}
if (C>=A && C>=B) {
System.out.println("The Higgest number is" +C);
}
First remove static before int, I don't see any use of it.
Follow Variables standard, instead of UPPER A,B,C use lowercase;
And here is the answer:
int highestNumber = Math.max(Math.max(a,b),c);
System.out.println("The Highest number is" +highestNumber);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I'm trying to get this to display the actual input instead of the option number.
import java.util.*;
public class RandomGenerator {
public static void main(String[] args) {
int length;
Scanner input = new Scanner(System.in);
System.out.println("How many options?"); //user input food options
length = input.nextInt();
String[] names = new String[length];
for(int counter = 0; counter < length; counter++){
System.out.println("Enter option #" + (counter+1) + ":");
names[counter] = input.next();
}
input.close();
System.out.println("You are going to eat " + new Random().nextInt(names.length));
You've already generated a random number here:
new Random().nextInt(names.length)
You can use this random number to access an element in the names array.
int randomNumber = new Random().nextInt(names.length);
String option = names[randomNumber]; // here is the important bit!
Now you can print option out!
System.out.println("You are going to eat " + option);
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
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.
Improve this question
My calculator does not work out the square root and I can not figure the problem out
My complete code:
package calculator; // package
import java.util.*;
public class Calculator { // start public access
// main method starts here
public static void main (String[] args) {
// declaring the variables to be used and the data types
double n1, n2;
String s1, s2;
String operation;
// prepare a new scanner for user input
Scanner scan = new Scanner(System.in);
// prompt user to input a valeu
System.out.println("Enter a number or press 0 to cancel: ");
n1 = scan.nextDouble();
s1 = String.valueOf(n1);
// check to see if 0 has been entered, if yes, then program will end
if (n1 != 0) {
// user has entered a valeu, prompt user for another value within the option to cancel the program
System.out.println("Enter a second nmber or press 0 to opt out: ");
n2 = scan.nextDouble();
s2 = String.valueOf(n2);
// check to see if 0 has been entred, if yes, then program will end
if (n2 != 0) {
// prompt user for operatoin to be carried out, +,-, *,/ and square root
Scanner op = new Scanner(System.in);
System.out.println("Enter +,-,/,qr: ");
operation = op.next();
// operation carried out depending on user input, result is displayed on the screen
switch (operation) {
case "+":
System.out.println("Your answer is " + (n1 + n2));
break;
case "-":
System.out.println("Your answer is " + (n1 - n2));
break;
case "/":
System.out.println("Your answer is " + (n1 / n2));
break;
case "*":
System.out.println("Your answer is " + (n1 * n2));
break;
case "qr":
n1 = Math.sqrt(n1);
System.out.printf("Your answer is %.2f, n1");
break;
default:
System.out.println("You are finished.");
} // end switch
} // end second if statement
}// end first if statement
} // end main
} // end the class'
When I run the code above, I am unable to work out the square root of a number, is there something wrong with my code.
I am new to programming so if you explain whats wrong, then it would be much appreciated.
System.out.printf("Your answer is %.2f, n1");
^ here is the error
This will throw a MissingFormatArgumentException. Your mistake is that you have included the required argument into the 'format' string. To resolve this, you need to add the argument after the 'format' string. Like this:
System.out.printf("Your answer is %.2f", n1);
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Im not sure how to go about making this code.. well at least the total part of this. this is my code right now, I understand the math behind it. I'm just not sure how to implement it. Would I use a loop? here is my code as of right now. I know its not correct but its the start of it.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("what number would you like me to multiply: ");
int number = in.nextInt();
System.out.println("how many multiples of "+number+" would you like to see: ");
int multiple = in.nextInt();
int total =
System.out.println("total :"+total);
}
here is the output that I would like to get:
What number would you like me to multiply? 4
How many multiples of 4 would you like to see? 7
The first 7 multiples of 4 are: 4, 8, 12, 16, 20, 24, 28
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("what number would you like me to multiply: ");
int number = in.nextInt();
System.out.println("how many multiples of "+number+" would you like to see: ");
int multiple = in.nextInt();
System.out.print("The first " + multiple + " multiples of " + number + " are: ");
for(int i=1; i<=multiple; i++){
if(i>1){
System.out.print(", ");
}
System.out.print(number*i);
}
}
Not for this site but:
String output = "The first " + multiples + " multiples of " + number + " are: "
for(int x = 1; x <= multiples; x++){
output = output + Integer.toString(x*number) + ",";
}
This can be improved using String.format but ill leave that to you.
Your code could also be improved by doing error checking because right now you could say 'a' for an input and it would crash.
You should look up the basics of programming and also just try stuff you'd be surprised by what you learn just doing random things. There is https://projecteuler.net/ if you need ideas about what to try.
I am new at programming so sorry if this is a stupid question, but I cant find the answer anywhere.
I have a scanner that asks for the answer of a math problem (the scanner expects a double to be the input). Naturally, most people would enter in a number as an answer, but if they put in something else (that can't be converted to a double) I am supposed to give them a message saying to put it in decimal form. The only problem is I am having a hard time figuring out out to tell the computer if (answer != double) then print out "blah, blah, blah". Currently if you input a letter or something, it gives a computer generated error message in red that I don't want. Is there a way to tell it to print out the message I want instead?
This is a small part of my program that contains the scanner in question:
if (letter.equalsIgnoreCase("A")) {
System.out.print("What is the solution to the problem: " + correctRange + " + " + correctRange2 + " = ");
// make the user answers a double variable
double answer;
answer = scnr.nextDouble();
double solution;
solution = correctRange + correctRange2;
// make a variable that is determined by if the answer is close
// enough
boolean close = ((solution + Config.CLOSE_ENOUGH) >= answer
&& answer >= (solution - Config.CLOSE_ENOUGH));
// give different responses based on if the user's answer was
// close
if (close) {
System.out.println("That is correct!");
} else {
System.out.println("The correct solution is " + solution + ".");
}
Use Scanner.hasNextDouble() e.g.
if (scanner.hasNextDouble()) {
double d = scanner.nextDouble();
// do something with d
} else {
scanner.nextLine(); // discard the line
System.err.println("Please enter a number");
}
You could either do
try{
result = scanner.nextDouble();
}catch (InputMismatchException ex){
System.out.println("blah blah");
}
or and even better
if (scanner.hasNextDouble()) {
result = scanner.nextDouble();
} else {
System.err.println("blah blah");
scanner.nextLine(); // discard the line
}