The goal of the project is to create a calculator which will let the user choose which operation to use, which will then be solved and added to a linked list. The last option is to see the history which are past answers or solutions.
I'm quite new and this is a project I'm really trying to finish on my own but I have researched and still can't seem to quite understand what or how to fix. Please explain to me so that I can understand better! Also please comment on the design or flow of my code. Thanks!
import java.util.Scanner;
import java.util.LinkedList;
public class projectOne {
public static void main(String[] args) {
int one = 0;
int two = 0;
int ans = 0;
int selection = 0;
Scanner scanner = new Scanner(System.in);
LinkedList l = new LinkedList();
do{
System.out.println("\nSelect an option: \n1. Addition \n2. Subtraction \n3. Multiplication \n4.Division \n5. See History");
selection = scanner.nextInt();
/* if (selection >= 1 && selection <= 4) {
System.out.println("\nEnter two numbers to be used in relevant calculation: ");
one = scanner.nextDouble();
two = scanner.nextDouble();
}
*/
switch(selection) {
case 1:
System.out.println("Performing Addition. \nEnter first number: ");
one = scanner.nextInt();
System.out.println("Enter second number: ");
two = scanner.nextInt();
System.out.println(one + " + " + two + " = " + (one + two));
ans = one + two;
l.append(ans);
break;
case 2:
System.out.println("Performing Subtraction. \nEnter first number: ");
one = scanner.nextInt();
System.out.println("Enter second number: ");
two = scanner.nextInt();
System.out.println(one + " - " + two + " = " + (one - two));
ans = one - two;
l.append(ans);
break;
case 3:
System.out.println("Performing Multiplication. \nEnter first number: ");
one = scanner.nextInt();
System.out.println("Enter second number: ");
two = scanner.nextInt();
System.out.println(one + " * " + two + " = " + (one * two));
ans = one * two;
l.append(ans);
break;
case 4:
System.out.println("Performing Division. \nEnter first number: ");
one = scanner.nextInt();
System.out.println("Enter second number: ");
two = scanner.nextInt();
System.out.println(one + " / " + two + " = " + (one / two));
ans = one / two;
l.append(ans);
break;
case 5:
System.out.println("History: \n" + l);
break;
}
} while(selection != 6);
}
}
LinkedList does not have method append, you can use add, addLast.
Also, please avoid using raw type, use LinkedList<Integer> instead.
Related
I incorporated a couple different methods I've seen on here. Does anyone know how to fix this problem I am having? When you use this code, It asks for you to enter the mathematical operator, BUT when I do if I enter +9 or -%, it will still work and use the first symbol. I want it to give an error if someone inputs */ instead of just *. I even tried switching the case to numbers (ie case 1:) and it will do the same thing if I set addition to 1 and if I enter 15, it will read the one and do addition. Any ideas?
import java.util.Scanner;
public class javacalculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Scanner operation = new Scanner(System.in);
double num1, num2, answer;
char userOperation;
System.out.print("Enter your full name: ");
String userName = input.nextLine();
System.out.println("+ Addition");
System.out.println("- Subtraction");
System.out.println("* Multiplication");
System.out.println("/ Division");
System.out.println("% Modulus");
System.out.println("\n");
System.out.print("Enter mathematical operator e.g. + for Addition: ");
userOperation = operation.next().charAt(0);
boolean invalidOperator = false;
switch (userOperation) {
case '+':
System.out.print("Enter first number: ");
num1 = input.nextInt();
System.out.print("Enter the second number: ");
num2 = input.nextInt();
answer = num1 + num2;
System.out.print(num1 + " + " + num2 + " = " + answer);
break;
case '-':
System.out.print("Enter first number: ");
num1 = input.nextInt();
System.out.print("Enter the second number: ");
num2 = input.nextInt();
answer = num1 - num2;
System.out.print(num1 + " - " + num2 + " = " + answer);
break;
case '*':
System.out.print("Enter first number: ");
num1 = input.nextInt();
System.out.print("Enter the second number: ");
num2 = input.nextInt();
answer = num1 * num2;
System.out.print(num1 + " * " + num2 + " = " + answer);
break;
case '/':
System.out.print("Enter first number: ");
num1 = input.nextInt();
System.out.print("Enter the second number: ");
num2 = input.nextInt();
answer = num1 / num2;
System.out.print(num1 + " / " + num2 + " = " + answer);
break;
case '%':
System.out.print("Enter first number: ");
num1 = input.nextInt();
System.out.print("Enter the second number: ");
num2 = input.nextInt();
answer = num1 % num2;
System.out.print(num1 + " % " + num2 + " = " + answer);
break;
default:
System.out.println("Invalid operator!");
break;
}
}
}
Let us break this down: operation.next().charAt(0);
operation.next() -> Gives you full input string
.charAt(0); -> returns the first character of the full input string
So anything we enter +9 or */ -> it returns the first element.
Now let's handle this case:
String o = operation.next(); // here is complete input
if(o.length()!=1){
userOperation = 0; //if length of input is not 1 we set custom value
}else{
userOperation = o.charAt(0); //get and set the first and only element
}
Hopefully it helps!
I am trying to make a program that solves for all the 2 number combinations of addition and subtraction that equal a target value.
For example, given the array [12,1,9,11,32,19] and the target value twenty, the answers 1+19, 9+11, and 32-12 must be returned. If there are no possible combinations, the System should print that there are no possible combinations. Also, every combination must be two numbers ONLY. Is it possible to do this only in the main class?
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("What length (in a whole number) would you like the array to be? ");
int arraySize = sc.nextInt();
int [] arr = new int[arraySize];
for (int i = 0; i < arraySize; i++) {
int remainingNumbers = arraySize - i;
System.out.println("Please enter " + remainingNumbers + " more integers.");
arr[i] = sc.nextInt();
}
System.out.print("Please enter a target value: ");
int target = sc.nextInt();
System.out.println(Arrays.toString(arr));
// Algorithm here.
}
}
import java.util.Scanner;
public class Exercise6 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Input first number: ");
int num1 = in.nextInt();
System.out.print("Input second number: ");
int num2 = in.nextInt();
System.out.println(num1 + " + " + num2 + " = " +
(num1 + num2));
System.out.println(num1 + " - " + num2 + " = " +
(num1 - num2));
System.out.println(num1 + " x " + num2 + " = " +
(num1 * num2));
System.out.println(num1 + " / " + num2 + " = " +
(num1 / num2));
System.out.println(num1 + " mod " + num2 + " = " +
(num1 % num2));
}
}
enter code here
''' Input first number: 32 Input second number: 12 19 + 1 = 20 32 - 12 = 20 9+11= 20'
Yes, it is possible to do it only in the main class. It is even possible to do it only in the main method (despite doing it an own method is better, easier to understand). Just two nested for loops; one for the first value, one for the second value. Inside the inner loop just test if the sum of both values result in the expected result, same for subtraction. Set a boolean to indicate that at least one case was found. At the end print the negative message if the boolean is not set.
Sample:
private static boolean findCombinations(int target, int[] values) { // or ,int... values) {
boolean found = false;
for (int i = 0; i < values.length; i++) {
// second loop
// tests and print
}
return found;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean start = true;
while(start)
System.out.printf("%70s %n", " ##### Zoos Australia ##### " + "\n");
System.out.printf("%57s %n", "Main Menu" + "\n");
System.out.printf("%72s %n", "Zoo has the following ticketing options:");
System.out.print("\n");
System.out.printf("%59s %n", "1 = Child (4-5 yrs)");
System.out.printf("%59s %n", "2 = Adult (18+ yrs)");
System.out.printf("%60s %n", "3 = Senior (60+ yrs)");
System.out.println("\n");
String choose1 = "";
String choose2 = "";
String choose3 = "";
String selected = "";
int option = 0;
{
System.out.print("Please select an option: ");
option = input.nextInt();
if (option == 1) {
choose1 = "Child";
selected = choose1;
} else if (option == 2) {
choose2 = "Adult";
selected = choose2;
} else if (option == 3) {
choose3 = "Senior";
selected = choose3;
}
}
// done
System.out.println("\n");
int price = 0;
int tickets = 0;
System.out.print("Enter the number of tickets: ");
tickets = input.nextInt();
if (selected == choose1) {
price = 10;
} else if (selected == choose2) {
price = 20;
} else if (selected == choose3) {
price = 15;
}
System.out.println("\n");
System.out.print("You are purchasing " + tickets + " " + selected + " tickets at " + "$" + price + " each!");
System.out.println("\n");
int confirm = 0;
System.out.print("Press 1 to confirm purchase: ");
confirm = input.nextInt();
if (confirm != 1) {
System.out.print("Incorrect Key. Please return to Main Menu");
System.out.println("\n");
} else {
break;
}
System.out.println("\n");
int total = tickets;
price = total * price;
System.out.print("Total amount for " + selected + " tickets: " + "$" + price);
System.out.println("\n");
String pick = "";
System.out.print("Do you wish to continue: ");
input.next();
System.out.println("\n");
if (pick == "no") {
System.out.print("Total amount payable is: " + "$" + price);
System.out.println("\n");
System.out.print("Have a nice day!");
System.out.println("\n");
}}}
Trying to do this at the end of the program where user is asked "Do you wish to continue" using a method or something but cant get it to work. Either the program returns to main menu only or the program ends and displays the total message "Total amount payable..." etc. I have tried using while with continue and break. Using boolean with true and false. But no luck. Thank you anyone that may be able to clear this up for me please.
First, you have to assign the users's input to a variable: pick = input.next(). After that, the problem is that you compare the user's input string with a "no" string by using == operator. When comparing reference types (objects) (and String is an object), in most cases == operator gives you an unpredictable result, because it compares the reference (address of an object in memory) and not the actual content. Please remember, that you always have to use the .equals() method instead. You also have to break from your loop, when the user's input is "no".
There is plenty of material concerning this issue. You can check, for instance, this one How do I compare strings in Java?
P.S. I quickly looked at the rest of your code and put some additional comments, which might help you to improve it. Good luck with learning Java!
Scanner input = new Scanner(System.in);
// boolean start = true; you don't need this line
while(true) { // 'true' condition makes it an infinite loop until you use break
// You also have to surround your while loop with curly braces,
// otherwise you fall into an infinite loop
System.out.printf("%70s %n", " ##### Zoos Australia ##### \n");
System.out.printf("%57s %n", "Main Menu\n");
System.out.printf("%72s %n", "Zoo has the following ticketing options: \n");
System.out.printf("%59s %n", "1 = Child (4-5 yrs)");
System.out.printf("%59s %n", "2 = Adult (18+ yrs)");
System.out.printf("%60s %n", "3 = Senior (60+ yrs)\n");
String choose1 = "";
String choose2 = "";
String choose3 = "";
String selected = "";
int option = 0;
System.out.print("Please select an option: ");
option = input.nextInt();
if (option == 1) {
choose1 = "Child";
selected = choose1;
} else if (option == 2) {
choose2 = "Adult";
selected = choose2;
} else if (option == 3) {
choose3 = "Senior";
selected = choose3;
}
System.out.println(); // "\n" is a redundant argument
int price = 0;
int tickets = 0;
System.out.print("Enter the number of tickets: ");
tickets = input.nextInt();
if (selected.equals(choose1)) { // you should never compare strings with == operator! Always use .equals() instead
price = 10;
} else if (selected.equals(choose2)) {
price = 20;
} else if (selected.equals(choose3)) {
price = 15;
}
System.out.println();
System.out.print("You are purchasing " + tickets + " " + selected + " tickets at " + "$" + price + " each!");
System.out.println();
int confirm = 0;
System.out.print("Press 1 to confirm purchase: ");
confirm = input.nextInt();
if (confirm != 1) {
System.out.print("Incorrect Key. Please return to Main Menu");
System.out.println("\n");
} else {
//break; you cannot use 'break' in the if statement! You have to figure out another way, how to handle an invalid input
}
System.out.println();
int total = tickets;
price = total * price;
System.out.print("Total amount for " + selected + " tickets: " + "$" + price);
System.out.println();
String pick = "";
System.out.print("Do you wish to continue: ");
pick = input.next(); // you have to assign the input to a variable
System.out.println();
if (pick.equals("no")) { // You have to ALWAYS use .equals() when comparing Strings or any other reference types! == works correctly only with primitive types
System.out.print("Total amount payable is: " + "$" + price);
System.out.println();
System.out.print("Have a nice day!");
System.out.println();
break; // you need to break from the loop in the end
}
}
}
My teacher wants us to make a program that counts the total number of votes for two candidates from a variable number of precincts. So the user inputs the candidates’ names as strings and is then prompted to enter the number of precincts prior to entering the votes for each precinct. What I am having trouble with is that I have to use an array to keep each precinct's vote total. Then after all of that is done I have to keep a running total of the votes for each candidate after each precinct is completed and who is currently leading and by how much. I have already begun my program but I am honestly just lost as to where to go from here, and I know that what I have in my arrays so far is not correct.
import java.util.*;
public class Voting
{
public static void main (String [] args)
{
Scanner scan = new Scanner(System.in);
int rerun;
int rerun2;
while (rerun == 1)
{
System.out.print("Name of candidate 1: ");
candidate1 = scan.next();
System.out.print("Name of candidate 2: ");
candidate2 = scan.next();
System.out.print("\nPlease enter amount of precincts: ");
presincts = scan.nextInt();
System.out.print("\n Please enter amount of votes for candidate 1: ");
votes1 = scan.nextInt();
System.out.print("\n Please enter amount of votes for candidate 2: ");
votes2 = scan.nextInt();
while (rerun2 == 1 && precincts >= 0 && votes1 >= 0 && votes2 >= 0)
{
int[] votes1 = new int[precincts];
for(int i = 0; i < votes1.length; i++)
{
votes1[i] = int [i];
System.out.println ("\n" + votes1);
}
int[] votes2 = new int[precincts];
for(int i = 0; i < votes2.length; i++)
{
votes2[i] = int [i];
System.out.println ("\n" + votes2);
}
}
}
}
}
I don't know what the function of rerun is so I've left it out of this answer.
First thing you're going to want to do is initialize your variables at the start of your class:
String candidate1;
String candidate2;
int precincts;
int vote1;
int vote2;
int total1;
int total2;
int[] votes1;
int[] votes2;
Note you had a typo in precincts
Then you need to get the name of the candidates and the number of precincts (you've done this correctly already):
Scanner scan = new Scanner(System.in);
System.out.print("Name of candidate 1: ");
candidate1 = scan.next();
System.out.print("Name of candidate 2: ");
candidate2 = scan.next();
System.out.print("\nPlease enter amount of precincts: ");
precincts = scan.nextInt();
Then you need to iterate through the number of precincts, and get the number of votes for each candidate from each precinct. You can do this by initializing an empty array which will keep the votes stored (eg, the votes for the first candidate in precinct 1 will be stored in votes1[0]). Additionally, the easiest way to keep a running total is to use a separate variable total1 and total2:
total1 = 0;
total2 = 0;
votes1 = new int[precincts];
votes2 = new int[precincts];
for (int i = 0; i < precincts; i++) {
System.out.print("\nPlease enter amount of votes for candidate 1 in precinct " + (i + 1) + ": ");
vote1 = scan.nextInt();
votes1[i] = vote1;
total1 = total1 + vote1;
System.out.print("\nPlease enter amount of votes for candidate 2 in precinct " + (i + 1) + ": ");
vote2 = scan.nextInt();
votes2[i] = vote2;
total2 = total2 + vote2;
}
From inside the for loop you can do things like print the current total votes for a candidate:
System.out.println(candidate1 + " has " + total1 + " votes in total");
And print out who is the current leader and by how many votes:
if (total1 > total2) {
System.out.println(candidate1 + " is winning by " + (total1-total2) + " votes");
} else {
System.out.println(candidate2 + " is winning by " + (total2-total1) + " votes");
}
recently started computer programming and I am stuck on a homework assignment. I created a loop but instead of going back to the top, it starts 1 step ahead of where I intended it to. (it's all listed in the comments I made in the coding. I have been trying to figure this out for the past 6 hours so it would greatly appreciated if someone can help me.
import java.util.Scanner;
import java.text.DecimalFormat;
public class Election
{
public static void main (String[] args)
{
DecimalFormat f = new DecimalFormat("##.00");
DecimalFormat n = new DecimalFormat("##");
float votesForPolly;
float votesForErnest;
float totalPolly = 0;
float totalErnest = 0;
String response;
int precinctsforpolly = 0;
int precinctsforernest = 0;
int precinctsties = 0;
Scanner scan = new Scanner(System.in);
System.out.println ();
System.out.println ("Election Day Vote Counting Program");
System.out.println ();
do
{
//point A
System.out.println("Do you wish to enter more votes? Enter y:n");
response = scan.next();
if (response.equals("y"))
{
//point B
System.out.println("Enter votes for Polly:");
votesForPolly = scan.nextInt();
System.out.println("Enter votes for Ernest:");
votesForErnest = scan.nextInt();
totalPolly = totalPolly + votesForPolly;
totalErnest = totalErnest + votesForErnest;
System.out.println("Do you wish to add precincts? Enter y:n");
response = scan.next();
while (response.equals("y"))
{
System.out.println("How many precincts voted for Polly: ");
precinctsforpolly = scan.nextInt();
System.out.println("How many precincts votes for Ernest: ");
precinctsforernest = scan.nextInt();
System.out.println("How many were ties: ");
precinctsties = scan.nextInt();
break;
//not returning to point A, instead it returns to point B
}
if (response.equals("n"))
{
break;
}
if (response.equals("n"))
{
break;
}
}
}
while (response.equals("n"));
System.out.println("Final Tally");
System.out.println("Polly received:\t " + n.format(totalPolly) + " votes\t" + f.format((totalPolly/(totalPolly + totalErnest))*100) + "%\t" + precinctsforpolly + " precincts");
System.out.println("Ernest received: " + n.format(totalErnest) + " votes\t" + f.format((totalErnest/(totalPolly + totalErnest))*100) + "%\t" + precinctsforernest + " precincts");
System.out.println("\t\t\t\t\t" + precinctsties + " precincts tied");
}
}
My guess is that the string response has already been determine to be y at the end of the loop which is why it skips the first step and jumps right back into the loop assuming my answer is already y.
You will just need to strip your code of unnecessary breaks and also handle the 2 responses differently. Your loop should also continue when the response is y, not the other way round.
See edited code below:
import java.util.Scanner;
import java.text.DecimalFormat;
public class Election
{
public static void main (String[] args)
{
DecimalFormat f = new DecimalFormat("##.00");
DecimalFormat n = new DecimalFormat("##");
float votesForPolly;
float votesForErnest;
float totalPolly = 0;
float totalErnest = 0;
String response;
int precinctsforpolly = 0;
int precinctsforernest = 0;
int precinctsties = 0;
Scanner scan = new Scanner(System.in);
System.out.println ();
System.out.println ("Election Day Vote Counting Program");
System.out.println ();
do
{
//point A
System.out.println("Do you wish to enter more votes? Enter y:n");
response = scan.next();
if (response.equals("y"))
{
//point B
System.out.println("Enter votes for Polly:");
votesForPolly = scan.nextInt();
System.out.println("Enter votes for Ernest:");
votesForErnest = scan.nextInt();
totalPolly = totalPolly + votesForPolly;
totalErnest = totalErnest + votesForErnest;
System.out.println("Do you wish to add precincts? Enter y:n");
String response2 = scan.next();//create a new response variable, so the loop doesn't confuse which response to break on
//I removed the inner loop. If you really intended for this to be an inner loop then the while(response2.equals("y")){} should be around the question, not after
if (response2.equals("y"))
{
System.out.println("How many precincts voted for Polly: ");
precinctsforpolly = scan.nextInt();
System.out.println("How many precincts votes for Ernest: ");
precinctsforernest = scan.nextInt();
System.out.println("How many were ties: ");
precinctsties = scan.nextInt();
}
//removed the unnecessary checks for when response in 'n'
}
}
while (response.equals("y"));
System.out.println("Final Tally");
System.out.println("Polly received:\t " + n.format(totalPolly) + " votes\t" + f.format((totalPolly/(totalPolly + totalErnest))*100) + "%\t" + precinctsforpolly + " precincts");
System.out.println("Ernest received: " + n.format(totalErnest) + " votes\t" + f.format((totalErnest/(totalPolly + totalErnest))*100) + "%\t" + precinctsforernest + " precincts");
System.out.println("\t\t\t\t\t" + precinctsties + " precincts tied");
}
}
if (response.equals("n"))
{
break;
}
breaks your while loop.
You might want to loop again if user's response if 'y'.
In that case, use while (response.equals("y"));
Your requirement is to break out if the user enters "n" but loop while the user input is "y", but your code says,
do{
.....
}while (response.equals("n"));
It should be,
while (response.equals("y"));
do {
//point A
System.out.println("Do you wish to enter more votes? Enter y:n");
response = scan.next();
if (response.equals("y"))
{
//point B
#code
if (response.equals("n")) //<--- this 'if' block will break the loop when response equals 'n'
{
break;
}
}
}
while (response.equals("n"));// <----- this means doing loop when response equals "n"
You can see my comment on above block of code, the loop will do one more time only when response equals 'n'. But when response equals 'n', the 'if' block at above of it will break the loop and the while (response.equals("n")) will be not checked.