How to make the value of number2 equal to number only once - java

I am trying to make the value of number2 the value of number for only the first iteration of the loop. The only ways I have been able to figure out is how to make the value of number2 to number for the whole equation. ex: if I put 3 + 3 + 3 = the equation comes out to be 6 since number2 is set to number for the whole time, and number is set to 3.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
// Identifiers
int i = 1; // This int is what makes a ">" be printed on every new line.
final String end = "=";
double number;
String input;
String input2;
int yes;
int index;
int length;
double math = 0;
double number2;
// Prompt for the user on how to input the numeric expression.
System.out.println("Enter your numeric expression in the following form:");
System.out.println("number operator number operator number =");
System.out.println("Leave a blank space after each number or operator.");
System.out.println("Example: 3.5 * 3 - 5 / 2.5 =" + '\n');
input = "0";
while (!input.equals(end)) {
input = scnr.next();
number = Double.parseDouble(input);
number2 = number;
// System.out.println("num2 is: " + number2);
System.out.println("input is: " + input);
System.out.println("number is: " + number);
input = scnr.next();
switch(input) {
case "+":
math = number2 + number; System.out.println("add" + math);
break;
case "-":
math = number2 - number; System.out.println("sub" + math);
break;
case "*":
math = number2 * number; System.out.println("mult" + math);
break;
case "/":
math = number2 / number; System.out.println("div" + math);
}
number2 = math;
// System.out.println("num2 is: " + number2);
}
System.out.println("Answer: " + math);
/* double hiu = 3 / 2 * 3 - 2 + 1 ;
System.out.println("yes " + hiu); */
}
}

The easiest solution would be to just move the code parsing the very first number out of the loop. You want it to happen once, not loop over it. Something like
String input = scanner.next();
double number = Double.parseDouble(input);
double number2;
while(!input.equals(end)) {
input = scanner.next();
switch(input) {
case "+":
input = scanner.next();
number2 = Double.parseDouble(input);
number = number + number2;
break;
case "-":
...
}
}

These are both solutions. You can also use a do-while loop, applying the logic of Sorifiend's answer. The deciding factors are going to be the trade-offs between computational complexity vs. code readability vs. modularity.
computational complexity:
if you are doing very many computations, and have no actual need to evaluate that the condition is met before setting the variable, then get that out of your loop.
code readability:
use a comment to establish the logic of pulling that process out of the loop. You need a variable declared outside of the loop to update/store your answer as the string is parsed. You may define this variable as 0.0 before parsing anything since this is a neutral value that will have no impact on the calculation.
modularity:
you do not want the external variable getting accidentally orphaned. This isn't particularly applicable to your use case. Just a concept to keep in mind as you progress through your journey.

Related

Is there a way to prevent decimal output of a double calculation?

Got this code here and I was wondering if it were possible to make the output that comes from either calculation systems be without a decimal/stop the value at the point before the decimal point. Or even convert a double to an int without any errors.
Please ignore the pointless do while loop at the start, I am aware.
Thank You for any help.
class Main{
public static void main(String[] args)
{
calculation(getSystemChoice());
}
public static int getSystemChoice()
{
Scanner input = new Scanner(System.in); //create scanner
int systemChoice;
do{
System.out.println("If you are using the Metric system, please enter a 1.");
System.out.println("If you are using the Imperial system, please enter a 2.");
System.out.println("To quit the program, please enter a 3.");
systemChoice = input.nextInt();
//Switch start
switch(systemChoice){
case 1:
systemChoice=1;
return systemChoice;
case 2:
systemChoice=2;
return systemChoice;
default: //Currently no working input correction system, likely due to no case for 3. !!!!
System.exit(0);
}
//Switch End
}
while(systemChoice != 1 || systemChoice != 2 || systemChoice != 3);
return systemChoice;
}
//This method takes an int as a parameter(1 or 2) and runs if statements based on the metric or imperial systems.
public static void calculation(int systemChoice)
{
double inches, centimeters, meters, feet;
Scanner input = new Scanner(System.in); //create scanner
//if the user entered one, the result will be in meters and centimeters
if(systemChoice == 1){
System.out.print("Enter amount of meters: ");
meters = input.nextDouble();
System.out.print("Enter amount of centimeters: ");
centimeters = input.nextDouble();
feet = meters * 3.28084;
inches = centimeters / 2.54;
System.out.printf("Feet: %.2f\t " , feet);
System.out.printf("Inches: %.2f\t " , inches);
rerun(systemChoice);
}
// if the user entered 2 then the result will be in feet and inches
else if(systemChoice == 2){
System.out.print("Enter amount of feet: ");
feet = input.nextDouble();
System.out.print("Enter amount of inches: ");
inches = input.nextDouble();
meters = feet / 3.28084;
centimeters = inches * 2.54;
System.out.printf("Meters: %.2f\t " , meters);
System.out.printf("Centimeters: %.2f\t\n " , centimeters);
rerun(systemChoice);
}
}
public static void rerun(int systemChoice)
{
Scanner in = new Scanner(System.in);
System.out.println("\nIf you would like to make another measurement, enter 4.");
System.out.println("Otherwise, you may quit by entering any other number.");
systemChoice = in.nextInt();
if(systemChoice == 4)
{
getSystemChoice();
calculation(systemChoice);
}
else
{
System.exit(0);
}
}
}
You can use casting just before you print it and print it as an integer.
System.out.printf("Inches: %d " , (int)inches)
I do not recommend simply casting to int. Here is an example:
double myValue = 8.65;
System.out.println((int) myValue); // will output 8 as java will always round to the next lower integer
System.out.println(Math.round(myValue)); // will output 9 which obviously is correct (mathematically speaking)
There are a number of potential solutions depending on your exact requirements. Other posters have already mentioned a couple. It's worth bearing in mind the pros and cons of each:
Simply casting to an int or long is the simplest method, but will always round down. It's probably fine for your training example. But in real-world applications, this can cause subtle bugs with values that a double can represent but an int or long can't (e.g. a double can represent the result of 1.0/0 as "infinity", but casting to an int or long will turn this into a large positive integer value-- that can lead to subtle bugs in real-world applications);
You can use Math.round() to use the convention of rounding to up or down to the 'nearest' integer; but this doesn't solve the issue of values that can't be represented;
For other rounding modes, you can use the BigDecimal class: see the BigDecimal.round() method-- many applications won't require this, but some specialist cases might;
To truncate to zero decimal places for output while also dealing with 'special' values, you can use String.format() and specify zero decimal places.
The code for the latter option would look as follows:
double val = ...
System.out.printf("Truncated value is: %.0f", val);
You've probably already seen the 'simple casting' option, but it would look like this:
double val = ...
long truncatedVal = (long) val;
System.out.println("Truncated value = " + truncatedVal);

Java number subtraction, decompose second number in a sum of 1

I'm making a simple while loop when i can make a subtraction between 2 number in java.
The only task of this exercise is this:
Suppose that user insert 2 number by this method (
Scanner keyboard = number.nextInt();
Scanner keyboard2 = number2.nextInt();
Suppose that user insert these 2 number : 8 and 3
I'm not asking for a program which makes 8 - 3 = 5
The program is able to do only substraction or addiction of 1.
so the five is converted in a substraction of -1 for five time.
So instead of 8 - 3, the program calculate 8 -1 -1 -1 -1 -1 = 3
// 8 - 5
Or :
8 -1 = 7
7 - 1 = 6
// ....
4 - 1 = 3
The exercise don't requires complex method, or for loop, only while
As my point of view, i think that you need your answer like your example. Because of that, i made a program for you. In this program if you only enter large number first, you can except if statement, This is my solution.
import java.util.*;
import java.lang.*;
public class Stack2{
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
int num1=sc.nextInt();
int num2=sc.nextInt();
if(num1<num2){
System.out.println("Number 1 is less than number 2");
System.exit(1);
}
int x=num1-num2;
System.out.print(num1+" - "+num2+" --> is equal to "+ num1+" " );
while(num1!=x){
System.out.print("-1 ");
num1--;
}
System.out.println("= "+x);
}
}
i'm not sure if you want some like this
int num1 = 8;
int num2 = 5;
int res = num1- num2;
boolean bandera = Boolean.TRUE;
String salida = "";
while(bandera)
{
if(num2 > 0)
{
salida = salida +"-1";
num2--;
}else
{
bandera = Boolean.FALSE;
}
}
System.out.println(num1 + salida + "=" + res);
Your code needs little correction. You haven't declared Scanner object correct and even numbers. Try this code,
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num1 = sc.nextInt();
int num2 = sc.nextInt();
System.out.print(num1 + " - " + num2 + " --> Is equal to " + num1);
while(num2 > 0) {
System.out.print(" - 1");
num1 -= 1;
num2--;
}
System.out.println(" = " + num1);
sc.close();
}

issues with java and printf and decimals

Code:
import java.util.Scanner;
public class sdusti00lab1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
double AA = 8.25;
double CA = 6.50;
double ACP = 9.00;
double CPC = 6.25;
int numA, numC;
double numSP, numLP;
Scanner keys = new Scanner(System.in);
System.out.print(" enter number of adults ");
numA = keys.nextInt();
System.out.println(" enter number of children ");
numC = keys.nextInt();
System.out.println(" enter number of small popcorn");
numSP = keys.nextDouble();
System.out.println(" enter number of large popcorn");
numLP = keys.nextDouble();
double AAddPrice = (numA*AA);
double CAddPrice = (numC*CA);
double ACPT = ((ACP*.094)*AA);
double CPCT = ((CPC*.094)*CA);
double SPTax = (ACP*.094);
double LPTax = (CPC*.094);
System.out.println("Adult admission "+"\t"+numA + "\t$" + AAddPrice);
System.out.println("Child admission "+"\t"+numC + "\t$" + CAddPrice);
System.out.println("Adult popcorn "+"\t\t"+ACP + "\t$" + ACPT);
System.out.println("Child popcorn "+"\t\t"+CPC + "\t$" + CPCT);
System.out.println("Tax "+"\t\t\t$"+ (SPTax + LPTax));
System.out.println("Total "+"\t\t\t$"+(AAddPrice+CAddPrice+CPCT+ACPT) );
}
}
I need to change the last 6 lines of code to produce a decimal that stops at the number second to the decimal, but I just don't know how to do that.
Use System.out.printf or System.out.format to do this. Use %.2f for printing upto two decimal point.
System.out.printf("Adult admission \t%d\t$%.2f%n", numA, AAddPrice);
There are various ways to turn numbers (float, double, ..) into formatted Strings. Oracle has a nice overview worth studying.
The important aspect to understand here: that process works by you
A) specifying a format that describes how your output should look like
B) you calling a formatter with that format and the numbers to format

How to divide variables in java for a GPA calculator

I'm currently working on a GPA calculator for a class of mine. I keep getting an error that has to do with the division I'm trying to do on the GPA calculation and am having trouble with the syntax for sub-strings and how to use them correctly. Below is the code I have so far. If you see anything I can fix that's not to complicated I'm open to all suggestions.
import java.util.Scanner;
public class GPA
{
public static void main(String[] mydata)
{
Scanner sc = new Scanner(System.in);
String choice = "";
String cnum;
String grade;
double points;
double gpa = 0;
int count = 0;
String credit= "", totalCredit = "";
while (!choice.equalsIgnoreCase("Q"))
{
cnum = (mydata[0]);
grade = (mydata[1]);
if (grade.equalsIgnoreCase("A")) {points = 4.0;}
else if (grade.equalsIgnoreCase("B")) {points = 3.0;}
else if (grade.equalsIgnoreCase("C")) {points = 2.0;}
else if (grade.equalsIgnoreCase("D")) {points = 1.0;}
else if (grade.equalsIgnoreCase("F")) {points = 0.0;}
credit = cnum.substring(3,4);
//System.out.println("credits = " + totalCredit);
System.out.println("GPA = " points/Double.parseDouble(credit));
System.out.print("Enter next course number and grade or ‘Q’ to quit: ");
System.out.println();
choice = sc.nextLine();
}
System.out.println("Bye!");
}
}
Not bad but there are a couple syntactical errors with your code:
The println argument needs to be concatenated with a +:
System.out.println("GPA = " + points / Double.parseDouble(credit));
The local variable, points, needs to be initialized since your if-else conditions are not exhaustive (ie: grade has a runtime range of A, B, C, D, or F but grade can technically be assigned to whatever is in mydata[1]). Either add an else condition or assign an initial value to points:
double points = 0.0;
Be sure to include + to concat the strings together :)
System.out.println("GPA = " + (points/Double.parseDouble(credit)));
I believe you want to be concatenating here.
System.out.println("GPA = " + (points/Double.parseDouble(credit)));
Instead of
System.out.println("GPA = " (points/Double.parseDouble(credit)));
And if you want
int theGpa = points/Double.parseDouble(credit));
System.out.println("GPA: " + theGpa);

Writing an infinite loop [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am writing code that should create an infinite loop, but is currently terminating unexpectedly.
When I either type in 'Y' for yes or 'N' for no, this code should enter a non-terminating loop.
import java.util.Scanner;
import java.text.NumberFormat;
import java.text.DecimalFormat;
public class Math_Island_XTENDED_Final
{
static Scanner sc = new Scanner(System.in);
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args)
{
//Declarations
int Bignumber;
int Mednumber;
int Smallnumber;
double addition;
double subtraction;
double multiplcation;
double division;
double sphere_radius1;
double sphere_radius2;
double sphere_radius3;
double rectangle_measurements;
char repeat;
String input;
System.out.println("Welcome to Math Island :D ! ");
System.out.println("We will use some numbers for our Formula ! ");
System.out.println("1 rule, NO DECIMALS !! ");
System.out.println("Please Pick a # from 1 to 100 NOW!! ");
Bignumber = sc.nextInt();
System.out.print("Please Pick a # from 1 to 20 NOW!! ");
Mednumber = sc.nextInt();
System.out.print("Please Pick a # from 1 to 5 NOW!! ");
Smallnumber = sc.nextInt();
//Results
addition = Bignumber + Mednumber + Smallnumber;
subtraction = Bignumber - Mednumber - Smallnumber;
multiplcation = Bignumber * Mednumber * Smallnumber;
division = Bignumber / Mednumber / Smallnumber;
sphere_radius1 = Bignumber * 3.14 * 3.14;
sphere_radius2 = Mednumber * 3.14 * 3.14;
sphere_radius3 = Smallnumber * 3.14 * 3.14;
rectangle_measurements = Bignumber * Mednumber * Smallnumber;
System.out.println();
System.out.println();
//results 2
System.out.println(" Your addition answer would be " + addition);
System.out.println(" Your subtraction answer would be " + subtraction);
System.out.println(" Your multiplcation answer would be " + multiplcation);
System.out.println(" Your division answer would be " + division);
System.out.println(" Your first sphere answer would be " + sphere_radius1);
System.out.println(" Your second sphere answer would be " + sphere_radius2);
System.out.println(" Your third sphere answer would be " + sphere_radius3);
System.out.println(" Your recangle size would be " + rectangle_measurements+ " in cubic Feet");
System.out.println();
System.out.println();
System.out.println("Would you like to Play again ? ");
System.out.println("Y for yes, & N for no " );
input = keyboard.nextLine();
repeat = input.charAt(0);
while (repeat == 'Y');
System.out.println();
while (repeat == 'N');
System.out.println();
System.out.println("Goodbye!");
}
}
You have semicolons after your while loops:
while (repeat == 'Y'); // <-- Right here
System.out.println();
If you remove it, you should get an infinite loop if repeat == 'Y' is true.
The same goes for the other loop. Just make sure you use braces around the code that you want to loop over:
while (repeat == 'Y')
System.out.println();
while (repeat == 'N') {
System.out.println();
System.out.println("Goodbye!");
}
If you want to use the loop to play the game again, I would recommend using a do/while loop, since you want to play at least once:
do {
System.out.println("Welcome to Math Island :D ! ");
System.out.println("We will use some numbers for our Formula ! ");
System.out.println("1 rule, NO DECIMALS !! ");
System.out.println("Please Pick a # from 1 to 100 NOW!! ");
Bignumber = sc.nextInt();
System.out.print("Please Pick a # from 1 to 20 NOW!! ");
Mednumber = sc.nextInt();
System.out.print("Please Pick a # from 1 to 5 NOW!! ");
Smallnumber = sc.nextInt();
//Results
addition = Bignumber + Mednumber + Smallnumber;
subtraction = Bignumber - Mednumber - Smallnumber;
multiplcation = Bignumber * Mednumber * Smallnumber;
division = Bignumber / Mednumber / Smallnumber;
sphere_radius1 = Bignumber * 3.14 * 3.14;
sphere_radius2 = Mednumber * 3.14 * 3.14;
sphere_radius3 = Smallnumber * 3.14 * 3.14;
rectangle_measurements = Bignumber * Mednumber * Smallnumber;
System.out.println();
System.out.println();
//results 2
System.out.println(" Your addition answer would be " + addition);
System.out.println(" Your subtraction answer would be " + subtraction);
System.out.println(" Your multiplcation answer would be " + multiplcation);
System.out.println(" Your division answer would be " + division);
System.out.println(" Your first sphere answer would be " + sphere_radius1);
System.out.println(" Your second sphere answer would be " + sphere_radius2);
System.out.println(" Your third sphere answer would be " + sphere_radius3);
System.out.println(" Your recangle size would be " + rectangle_measurements+ " in cubic Feet");
System.out.println();
System.out.println();
System.out.println("Would you like to Play again ? ");
System.out.println("Y for yes, & N for no " );
input = keyboard.nextLine();
repeat = input.charAt(0);
} while (repeat == 'y');
System.out.println("Goodbye!");*
encase the entire code in a while loop
define repeat as a boolean before the while loop- set it as True
then replace
while (repeat == 'Y') {
System.out.println();
}
while (repeat == 'N') {
System.out.println();
System.out.println("Goodbye!");
}
with an if statement that checks if the user input is "n", in which case change repeat to False. Otherwise keep repeat as True.
Also- lots of syntax errors in the code- clean those up and you should be fine
Take all the code you want to repeat and put it inside of its own function:
void myMathGame() {
//code for one round: setup, get user input, calculate values, print them
}
Then simply construct an unconditional infinite loop inside of your main function which you break if the user doesn't want another round:
public static void main(String[] args) {
while (true) {
myMathGame();
System.out.println("Would you like to Play again? (Y/N) ");
if (keyboard.nextLine().charAt(0) != "Y") {
break;
}
}
}

Categories

Resources