I cannot seem to make my code work properly. I need to find the area of the square and add the units of measurement depending on what the user uses either in for inch, m for meter, cm for centimeter, and ft for feet.
public static void main (String[] args)
{
// create scanner to read the input
Scanner sc = new Scanner(System.in);
//prompt the user to enter one side of the length
System.out.println("Enter one side of lenght of the square:");
double side1 = sc.nextDouble();
while (side1 < 0)
{
//prompt the user to enter the input again in a positive value
System.out.println("Error, No Negative Number. Enter again:");
side1 = sc.nextDouble();
}
char unitsMeasurement;
// prompt the user to enter the measurement unit
char units = Character.toUpperCase(status.charAt(0));
String unitsMeasurement = "";
**{
switch(units)
{
case "in":
unitsMeasurement = "inch"; break;
case "cm":
unitsMeasurement = "centimeter"; break;
case "ft":
unitsMeasurement = "feet"; break;
case "m":
unitsMeasurement = "meter"; break;
default:System.out.println("Invaild unit"); break;
}**
//Area of Square = side*side
double area = side1*side1;
**System.out.println("Area of Square is: "+area, +unitsMeasurement+);**
}
}
}
Your main problem is, that you are using a switch-case-statement on a char while all your cases are based on a String. That doesn't work together.
Some other problems are that status is never defined, therefore units can't have a value at all.
I'm not quite sure what you are trying to achieve, but I assume the following:
The user inputs the length of a square with a unit (abbreviated). The program calculates the area of the square and outputs it together with the unit (unabbreviated).
Sample input:
5cm
Sample output:
Area of square is: 25 centimeter^2
Keep in mind that an area has a squared length unit!
Based on that, here is some working code:
public static void main (String[] args) {
// create scanner to read the input
Scanner sc = new Scanner(System.in);
//prompt the user to enter one side of the length
System.out.println("Enter one side of lenght of the square:");
String input = sc.nextLine();
//Remove anything but digits
double side1 = Double.parseDouble(input.replaceAll("\\D+",""));
//Remove all digits
String unit = input.replaceAll("\\d","");
System.out.println(side1);
System.out.println(unit);
while (side1 < 0) {
//prompt the user to enter the input again in a positive value
System.out.println("Error, No Negative Number. Enter again:");
input = sc.nextLine();
//Remove anything but digits
side1 = Double.parseDouble(input.replaceAll("\\D+",""));
}
switch(unit) {
case "in":
unit = "inch";
break;
case "cm":
unit = "centimeter";
break;
case "ft":
unit = "feet";
break;
case "m":
unit = "meter";
break;
default:
System.out.println("Invaild unit");
break;
}
double area = side1*side1;
System.out.println("Area of Square is: " + area + " " + unit + "^2");
}
Related
Asking a user to input calculator mode and operation.
then make a while loop after getting user input.
I have to do all operations once I receive the input I can't seem to get user input and calculate the code
import java.util.Scanner;
public class loopsProject {
public static void main(String[] args) {
System.out.println("Hello Codiva");
Scanner scnr = new Scanner(System.in);
String mode;
String operator;
double numOne;
double numTwo;
double numThree;
double numofdValues;
String result;
//asking user to enter mode
System.out.print("Enter the calculator mode: Standard/Scientific?");
mode = scnr.nextLine();
while (mode.equals("Standard")) {
System.out.println("Enter '+' for addition, '-' for subtractions, '*'
for multiplication, '/' for division");
operator = scnr.nextLine();
}
while (numOne != 0 && numTwo != 0 && numThree !=0)
if (operator.equals("+")) {
System.out.println("How many numbers would you like to add?");
numofdValues = scnr.nextDouble();
System.out.println("Enter + numofdValues + numbers");
numOne = scnr.nextDouble;
numTwo = scnr.nextDouble;
numThree = scnr.nextDouble;
result = numOne + numTwo + numThree;
System.out.println("Your added answer is:" + result);
}
if (operator.equals("-")) {
System.out.println("How many numbers would you like to subtract?");
numofdValues = scnr.nextDouble();
System.out.println("Enter + numofdValues + numbers");
num1 = scnr.nextDouble;
num2 = scnr.nextDouble;
num3 = scnr.nextDouble;
result = numOne - numTwo - numThree;
System.out.println("Your subtracted answer is:" + result);
}
if (operator.equals("*"))
System.our.println("Your multiplied answer is:" + result);
if (operator.equals("/"))
if (operator.equals("invalid")) {
System.out.println("Your imput is invalid, please try again");
}
You mentioned you're having trouble with
setting up the user input for the entire problem
Hopefully this will provide you with the structure to move forward. You have two while loops, but you need one outside to control the looping of the user choosing modes or quitting.
public class loopsProject {
public static void main(String[] args) {
System.out.println("Hello Codiva");
//Your variables here
//asking user to enter mode
System.out.print("Enter the calculator mode: Standard/Scientific?");
mode = scnr.nextLine();
//This loop controls the mode, user will keep on entering or they can quit
while (!mode.equals("Quit")) {
if (mode.equals("Standard")) {
//your Standard logic
}
else if (mode.equals("Scientific")) {
//your Scientific logic
}
else {
//Handle however you want or quit
break;
}
//Ask user for input again
System.out.print("Enter the calculator mode: Standard/Scientific?");
mode = scnr.nextLine();
}
}
}
if operation is invalid reprompt the user again
For the case when operations are invalid, what you can do is just tell the user the operation is invalid and continue to skip asking them for input. That way it retains the mode and will restart the logic in the next loop. This would go inside your Standard logic or Scientific logic, each time you need to validate the user's input.
if (...) { //your checks for user input invalid operation here
System.out.println("Invalid operation, please retry.");
continue;
}
I have the following code, where the idea is that the user will input two numbers and the sum of the two will be calculated.
If an invalid value, e.g. a character is entered, an error message should be outputted but I keep getting errors
Java
package calculator;
import java.util.Scanner;
public class calculator {
/**
* #param args
*/
public static void main(String[] args) {
double n1, n2;
String operation;
Scanner scannerObject = new Scanner(System.in);
System.out.println("Enter first number");
n1 = scannerObject. nextDouble();
System.out.println("Enter second number");
n2 = scannerObject. nextDouble();
Scanner op = new Scanner(System.in);
System.out.println("Enter your operation");
operation = op.next();
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 asnwer is " + (n1 * n2));
break;
default:
System.out.println("I do not know!");}
}
int function(){
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer between 1-100: ");
int range;
while(true){
if(input.hasNextInt()){
range = input.nextInt();
if(0<=range && range <= 100)
break;
else
continue;
}
input.nextLine(); //Comsume the garbage value
System.out.println("Enter an integer between 1-100:");
}
return range;
}
}
and these are the error messages I get:
Errors
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextDouble(Scanner.java:2456)
at calculator.calculator.main(calculator.java:14)
I've tried so many different things but can't get it to work as I want it.
Can anyone be of any assistance here?
Thanks for reading
This exception is thrown by an instance of the Scanner class to indicate that a retrieved token does not match the pattern for the expected type, or that the retrieved token is out of range.
You can see the documentation for the exception here: https://docs.oracle.com/javase/7/docs/api/java/util/InputMismatchException.html
Taken from documention on Scanner
double nextDouble()
Returns the next token as a long. If the next token is not a float or
is out of range, InputMismatchException is thrown.
I suspect that your not inputting your number correctly. Ensure that your input is of the correct format.
You should also set the locale of your scanner as some locales expect a comma , instead of a dot ., such as:
Scanner scanner = new Scanner(System.in).useLocale(Locale.US);
Your first two inputs should be numbers. If this is true, then it's probably the decimal mark for your numbers. You need a dot(.) not a comma (,)
It seems that you are not entering any integer as input.
You can solve this by handling the exception this way :
try {
if(input.hasNextInt()){
range = input.nextInt();
if(0<=range && range <= 100)
break;
else
continue;
}
input.nextLine();
}
catch (InputMismatchException e) {
input.nextLine();
}
Your issue is at,
scannerObject. nextDouble();
You are trying to get a double but entering a string. You will need to do some sort of a input validation like below to stop program from crashing incase of invalid inputs.
try {
System.out.println("Enter first number");
n1 = scannerObject. nextDouble();
}
catch(InputMismatchException inEx) {
System.out.println("Invalid input");
}
Then you may want to create a loop to get the input again and agin until valid input is detected.
Edit
You'll need to,
import java.util.InputMismatchException;
Also create a loop to get a valid input from a user. Something like below. This is just an example, you'll need to do something like this to work with your code. Also need to make sure n1 and n2 are initiated before you actually use their values.
boolean notValidInput = true;
while(notValidInput) {
try {
System.out.println("Enter first number");
n1 = scannerObject. nextDouble();
notValidInput = false;
}
catch(InputMismatchException inEx) {
System.out.println("Invalid input. Please try again!");
}
}
Use a switch statement to implement a menu. Allow the user to enter correct upper/lowercase letters (i.e. AIR or air or Air or aiR etc ). If the user enters an invalid selection your program should tell them and then exit.
The answers for air, water and steel must use printf. Display air to 3 decimal places, water to 4 decimal places and steel to 5 decimal places.
After the user enters the distance the sound wave must travel but before using the number in a calculation, validate it. If the distance is less than zero or greater than 10000, display an error message and do no further processing ie exit. Nest the switch statement (menu – see above) within this if statement.
import java.util.Scanner;
public class SpeedSound
{
public static void main(String[] args)
{
String input;
double distance;
double time;
final double AIR = 1/1100;
final double WATER = 1/4900;
final double STEEL = 1/16400;
Scanner kyb = new Scanner(System.in);
System.out.print("Enter the corresponding medium:\n ");
System.out.println("Air\n ");
System.out.println("Water\n ");
System.out.println("Steel\n ");
input = kyb.nextLine();
System.out.print("Enter the distance: ");
distance = kyb.nextDouble();
if (distance < 0 || distance > 10000)
System.out.print("Error: ");
switch (input)
{
case "Air":
case "AIR":
time = (distance / 1100);
System.out.println("The total time traveled is " + time + "seconds.");
break;
case "Water":
case "WATER":
time = (distance / 4900);
System.out.println("The total time traveled is " + time + "seconds.");
break;
case "Steel":
case "STEEL":
time = (distance / 16400);
System.out.println("The total time traveled is " + time + "seconds.");
break;
}
}
}
Indentation doesn't matter for java, use a block by using {} braces, otherwise it will only execute the next statement.
if (condition) {
// .. lots of
// .. lines of
// .. code
}
Allow the user to enter correct upper/lowercase letters (i.e. AIR or air or Air or aiR etc )
As you need to handle all the lower/upper case version of the input. Just convert the string into lower casebefore passing to switch case, then define there only lowercase case statements instead of multiple statements.
intput = input.toLowerCase(); // this is not require if you have converted it earlier
switch (input) {
case "air":
If the user enters an invalid selection your program should tell them and then exit.
You can use the if condition and exit the user:
input = kyb.nextLine().toLowerCase();
if (! (input.equals("air") || input.equals("water") || input.equals("steel")) ) {
System.out.println("Invalid input. Exit");
return;
}
If the distance is less than zero or greater than 10000, display an error message and do no further processing ie exit.
if (distance < 0 || distance > 10000) {
System.out.print("Error: ");
return;
}
i am new to a java program and i have a homework where when i get input from a user as an string, i have to convert it to a double and multiple it with a .11111 using a switch decision structure.
A string input from user has to be a number in roman numeral which is I, II, III, IV, and so on....
//This is my program
package practiceNum;
import java.util.Scanner;
public class practiceNum{
class stastic void main(String[] args){
String num_In_Roman; //declare a string
Scanner keyboard = new Scanner(System.in); //read input words
System.out.println("Enter a roman numerals from I to X: "); //asking user input
num_In_Roman = keyboard.nextLine();
switch(num_In_Roman){
case "I":
break;
case "II":
break;
//and so on until 10 (X) in roman numerals.
default:
System.out.println("Invalid Number!");
}
//end of body program here
}
}
Here's what i did to calculate my math but still giving me an error.
Double value = Double.parseDouble(num_In_Roman); //convert string into double
case "I":
value *= .111111;
System.out.println(value);
break;
someone help please.
This is the bad way, but this is what you can do:
case "I":
value = 1 * .111111;
System.out.println(value);
break;
case "II":
value = 2 * .111111;
System.out.println(value);
break;
import java.util.*;
class Sept1Little {
public static void main (String args []) {
Scanner s = new Scanner(System.in);
System.out.println("Hey! I'm not gonna program today o.o but I'm gonna do a little program :3");
System.out.println("Let's play with some math!");
System.out.println("Enter two numbers and magic will happen");
System.out.print("Enter the first number: ");
float a = s.nextInt();
System.out.print("Enter the second number: ");
float b = s.nextFloat();
float c = (float) Math.pow( a, b);
System.out.printf("The number is :%f\n" , c);
System.out.println("We love Bernie Sanders!");
System.out.println("Come on, let's push him over the line!");
int poll1 = 30;
System.out.println("Current poll amount: " + poll1);
System.out.println("Let's add 7% and an extra 1%!");
int poll2 = poll1 + 7;
int poll3 = ++poll2;
System.out.println("Bernie Sanders would get :" + poll3 + ". Bernie would get a better percentage than Hillo Clinto-Money");
System.out.println("Write in the best US President Nominee: ");
String president = Keyboard.readString();
if (president.equals("Bernie Sanders")){
System.out.println("You chose Bernie Sanders.");
}
else if (president.equals("Donald Trump")) {
System.out.println("You chose Donald Trump");
}
else if (president.equals("Hillary Clinton")) {
System.out.println("You chose Hillary Clinton ");
}
else {
System.out.println("Choose someone we know...");
}
System.out.println("Let's calculate how much money you owe the govt by... SQUARE ROOTING IT!");
System.out.print("Enter the amount of money you owe the govt: ");
float debt1 = Keyboard.readFloat();
System.out.printf("The amount is now :%f\n" , Math.sqrt(debt1));
System.out.println("Welcome to the Euro to Dollar Convertor!");
System.out.print("Enter the amount in US Dollars you wish to convert to Euro: ");
float euro1 = Keyboard.readFloat();
final float rate = (float) 1.13;
System.out.printf("The amount in Euro is %f\n" , euro1 / rate);
}
}
As you can see, I am using Keyboard.readString(); when I ask for the nominee. When I use s.readLine();, it doesn't work, it skips to the else clause and then it crashes since it takes the president input for the float value afterwards. I'm sorry that it is a bit political but I didn't bother fiddling with it. When I put "Bernie Sanders" as "BernieSanders", I don't get the error, anyone knows why?
I guess that it is because s.nextFloat(); and s.nextInt(); only reads the float and the int, respectively, not the full line so the cursor of the Scanner it's after the float or the int and not in the next line. Here an example:
If your input it's:
5 Bench
Prove
And you have in your code:
a= s.nextInt(); //5
b= s.nextLine(); //" Bench"
Why it isn't catching the Prove value? Because after using s.nextInt() the cursor of the Scanner it's after the 5 and not in the next line (the line in which we have Prove). To avoid it you have to read the rest of the line (useless for you because you don't want it) but without getting this value. Like this:
a= s.nextInt(); //5
s.nextLine(); //We go to the next line
b= s.nextLine(); //"Prove"
P.S.: You have to use s.nextLine(); each time you use a s.nextInt(); or s.nextFloat(); as the example that I put above.
I expect it will be helpful for you!