How to sum elements of a stack - java

import java.util.*;
public class multiple {
public static int userNumber;
public static int userChoice;
static Stack<Object> stack = new Stack<Object>();
static int[] list = new int[100];
public static void main(String[] args) {
introduction();
multiple();
printStack(stack);
}
public static void introduction() {
Scanner input = new Scanner(System.in);
System.out.print("Welcome to the program, please enter the number less than 100 that you would like "
+ "to find whoes number \nbelow have muliples of 3 and 5: ");
userNumber = input.nextInt();
System.out.println();
// System.out.println("Ok, now that youve entered," + userNumber +
// " we will find out which numbers of you number are three and five. "
// +
// "would you like the result published as a:\n 1.alist \n 2.A sum of the result \n 3.Or both?");
// userChoice = input.nextInt();
// if (userChoice >=1 && userChoice <=3)
// System.out.println( "The Computer will now program for" +
// userChoice);
// else
// System.out.println("incorrect entry for menu. Please try again");
}
public static void multiple() {
for (int i = 1; i < userNumber; i++) {
if (i % 3 == 0 || i % 5 == 0) {
stack.push(i);
}
}
}
// public static addElementsofstac
private static void printStack(Stack<Object> s) {
if (s.isEmpty())
System.out.println("You have nothing in your stack");
else
System.out.println(s);
}
}
I am trying to make a simple program that will take input for a user, find out the multiples of 3 & 5, then return the sum of the multiple. I have all the multiples discovered. I have a hunch that i need to convert the stack to an array. if so, would i just use stack.toArray()? then i would add them in a for loop?

Alternative without the need for intermediary counter variable:
int sum = 0;
while (stack.size() > 0) sum += stack.pop();

Why would you need an array?
You just need to do something along the lines of:
int sum = 0;
for(i=0;i<stack.size();i++){
sum = sum + stack.pop();
}
Though I agree with the others in that there's really no purpose of the stack itself.
EDIT: your clarification is only more confusing. How are 3, 6 and 9 multiples of 10? Are you talking about integers less than an inputted number that are multiples of 3 and 5?

I usually do this way:
ArrayDeque<Integer> stack = new ArrayDeque<Integer>();
int ans = 0;
<...>
for (Integer n : stack) {
ans += n;
}

Related

Store user input in array multiple times

I'm working on a project which...
Allows the user to input 4 numbers that are then stored in an array for later use. I also want every time the user decided to continue the program, it creates a new array which can be compared to later to get the highest average, highest, and lowest values.
The code is not done and I know there are some things that still need some work. I just provided the whole code for reference.
I'm just looking for some direction on the arrays part.
*I believe I am supposed to be using a 2-D array but I'm confused on where to start. If I need to explain more please let me know. (I included as many comments in my code just in case.)
I tried converting the inputDigit(); method to accept a 2-D array but can't figure it out.
If this question has been answered before please redirect me to the appropriate link.
Thank you!
package littleproject;
import java.util.InputMismatchException;
import java.util.Scanner;
public class littleProject {
public static void main(String[] args) {
// Scanner designed to take user input
Scanner input = new Scanner(System.in);
// yesOrNo String keeps while loop running
String yesOrNo = "y";
while (yesOrNo.equalsIgnoreCase("y")) {
double[][] arrayStorage = inputDigit(input, "Enter a number: ");
System.out.println();
displayCurrentCycle();
System.out.println();
yesOrNo = askToContinue(input);
System.out.println();
displayAll();
System.out.println();
if (yesOrNo.equalsIgnoreCase("y") || yesOrNo.equalsIgnoreCase("n")) {
System.out.println("You have exited the program."
+ " \nThank you for your time.");
}
}
}
// This method gets doubles and stores then in a 4 spaced array
public static double[][] inputDigit(Scanner input, String prompt) {
// Creates a 4 spaced array
double array[][] = new double[arrayNum][4];
for (int counterWhole = 0; counterWhole < array.length; counterWhole++){
// For loop that stores each input by user
for (int counter = 0; counter < array.length; counter++) {
System.out.print(prompt);
// Try/catch that executes max and min restriction and catches
// a InputMismatchException while returning the array
try {
array[counter] = input.nextDouble();
if (array[counter] <= 1000){
System.out.println("Next...");
} else if (array[counter] >= -100){
System.out.println("Next...");
} else {
System.out.println("Error!\nEnter a number greater or equal to -100 and"
+ "less or equal to 1000.");
}
} catch (InputMismatchException e){
System.out.println("Error! Please enter a digit.");
counter--; // This is designed to backup the counter so the correct variable can be input into the array
input.next();
}
}
}
return array;
}
// This will display the current cycle of numbers and format all the data
// and display it appropriatly
public static void displayCurrentCycle() {
int averageValue = 23; // Filler Variables to make sure code was printing
int highestValue = 23;
int lowestValue = 23;
System.out.println(\n--------------------------------"
+ "\nAverage - " + averageValue
+ "\nHighest - " + highestValue
+ "\nLowest - " + lowestValue);
}
public static void displayAll() {
int fullAverageValue = 12; // Filler Variables to make sure code was printing
int fullHighestValue = 12;
int fullLowestValue = 12;
System.out.println(" RESULTS FOR ALL NUMBER CYCLES"
+ "\n--------------------------------"
+ "\nAverage Value - " + fullAverageValue
+ "\nHighest Value - " + fullHighestValue
+ "\nLowest Value - " + fullLowestValue);
}
// This is a basic askToContinue question for the user to decide
public static String askToContinue(Scanner input) {
boolean loop = true;
String choice;
System.out.print("Continue? (y/n): ");
do {
choice = input.next();
if (choice.equalsIgnoreCase("y") || choice.equalsIgnoreCase("n")) {
System.out.println();
System.out.println("Final results are listed below.");
loop = false;
} else {
System.out.print("Please type 'Y' or 'N': ");
}
} while (loop);
return choice;
}
}
As far as is understood, your program asks the user to input four digits. This process may repeat and you want to have access to all entered numbers. You're just asking how you may store these.
I would store each set of entered numbers as an array of size four.
Each of those arrays is then added to one list of arrays.
A list of arrays in contrast to a two-dimensional array provides the flexibility to dynamically add new arrays.
We store the digits that the user inputs in array of size 4:
public double[] askForFourDigits() {
double[] userInput = new double[4];
for (int i = 0; i < userInput.length; i++) {
userInput[i] = /* ask the user for a digit*/;
}
return userInput;
}
You'll add all each of these arrays to one list of arrays:
public static void main(String[] args) {
// We will add all user inputs (repesented as array of size 4) to this list.
List<double[]> allNumbers = new ArrayList<>();
do {
double[] numbers = askForFourDigits();
allNumbers.add(numbers);
displayCurrentCycle(numbers);
displayAll(allNumbers);
} while(/* hey user, do you want to continue */);
}
You can now use the list to compute statistics for numbers entered during all cycles:
public static void displayAll(List<double[]> allNumbers) {
int maximum = 0;
for (double[] numbers : allNumbers) {
for (double number : numbers) {
maximum = Math.max(maximum, number);
}
}
System.out.println("The greatest ever entered number is " + maximum);
}

how do i repeatedly multiply a number in java by 2 until it reaches 1 million?

import java.util.Scanner;
class Main {
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
int testNumber = userInput.nextInt();
do{
System.out.println(newNumber * 2);
newNumber++;
}while( testNumber < 1000000);
}
}
You need to update the number after you multiply it by 2:
newNumber = newNumber * 2;
System.out.println(newNumber);
Also you are using newNumber and testNumber and newNumber doesn't appear to be defined anywhere...
}while( ***testNumber***newNumber*** < 1000000);
You need to pick one because if you are updating newNumber but comparing testNumber in your loop you will have created an infinite loop.
The code you have shown shouldn't compile unless you are leaving something out of your post.
You have the right idea with your loop, but you have multiple problems with your variables.
Your first problem is that you read in a variable from the user - testNumber, but then you are (incorrectly) manipulating a completely different variable - newNumber.
Your second problem is that you are testing the unchanged variable as your stop condition.
You probably want your loop to be something like:
do {
testNumber = testNumber * 2;
System.out.println(testNumber);
} while(testNumber < 1000000);
You can also make a recursive method for it.
public int reachMillion(int num) {
if(num<=0)
return -1; // indicating it is not possible.
if(num>=1000000) // Base Condition denoting we have reached 1 million
return num;
return reachMillion(num*2); // recursive part to multiply by 2 until we reach 1 million
}
class Main {
private static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
int newNumber = 0;
do{
System.out.println("Enter a positive number: ");
try{
newNumber = userInput.nextInt();
}catch(Exception ignored){ }
System.out.println("");
}while(newNumber <= 0);
System.out.println("----- " + newNumber + " multiply by 2 ------");
while(newNumber <= 1_000_000){
System.out.print("2 * " + newNumber +" = ");
newNumber <<= 1;//in some compilers left shift is faster than multiply
System.out.println(newNumber);
}
}
#brso05 has done well describing what went wrong here. I'd like to offer a complete example:
import java.util.Scanner;
public class Main {
private static Scanner userInputScanner = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Please input a number: ");
int userInputNumber = userInputScanner.nextInt();
System.out.println();
int newNumber = userInputNumber;
while (newNumber < 1_000_000) {
newNumber *= 2; // Take the variable on the left, multiply it by the number on the right, and save it in the variable on the left
System.out.println(newNumber);
}
}
}
Try it online!
Beware! That code does not handle any bad user input. For instance, if you give it 0, it will loop forever, and if you give it foo, it will crash. In case you want to handle all the edge cases of user input, this will do that:
import java.util.*;
public class Main {
private static Scanner userInputScanner = new Scanner(System.in);
public static void main(String[] args) {
int userInputNumber;
//
while(true) {
System.out.print("Please input a number: ");
if (userInputScanner.hasNext()) {
// The user gave us something, but we don't know if it's a number
String rawUserInput = userInputScanner.next();
try {
userInputNumber = Integer.parseInt(rawUserInput);
// If that previous line runs, the user has given us an integer!
System.out.println();
if (userInputNumber > 0) {
// The user has given a valid number. Break out of the loop and multiply it!
break;
}
else {
// The user has given a bad number. Tell them why and ask again.
System.out.println("The number has to be greater than 0.");
}
}
catch (NumberFormatException exception) {
// The user has given us something, but it wasn't an integer
System.out.println();
System.out.println("That is not a number: " + exception.getMessage());
}
}
else {
// There is no input, so we can't do anything.
return;
}
}
// Done looping through user input
int newNumber = userInputNumber;
while (newNumber < 1_000_000) {
newNumber *= 2; // Take the variable on the left, multiply it by the number on the right, and save it in the variable on the left
System.out.println(newNumber);
}
}
}
Try it online!
There is a tricky part of do-while loops. In that type of loops, do part is executed firstly. For the example below, although the input is already bigger than 1000000, it prints 1000001.
public void doWhileLoop() {
int num = 1000001;
do {
System.out.println(num);
num *= 2;
} while (num < 1000000);
}
Therefore, it will be a good idea to use some guard-clauses (aka, if-statements) before doing something in do-while loops. Like,
public void doWhileLoop() {
int num = 1000001;
if(num >= 1000000) {
return;
}
do {
System.out.println(num);
num *= 2;
} while (num < 1000000);
}

Count How many number multiple by the number from input user between a range

again I have a problem with doing practice prepare for the exam.
Would everyone help me? Thanks a lot
write a program input an integer in the range 100 to 200 inclusive. If the user enters invalid input then your algorithm should re-prompt the user until the input is valid. Your algorithm should then count how many numbers between 500 and 1000 which are multiples of the number input. Finally, the count should be output to the user. You should make good use of sub-modules.
Here my code
import java.util.*;
public class Exam3
{
public static void main(String args[])
{
int count = 0;
int input = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number: ");
input = sc.nextInt();
while(input < 100 || input > 200)
{
System.out.println("Enter number between 100 to 200");
input = sc.nextInt();
count ++;
}
System.out.println("count is: " + count);
}
public static void int getCount(int input, int count)
{
for(int i = 499;i <= 1000; i++ )
{
if(i % input==0)
{
count++;
}
}
return count;
}
}
The algorithm should be:
Having correct input, find all multiples of it that are in range [500, 1000]. Count them.
It's a bad approach to check all the numbers, as we know from our math knowledge, that between k*a and k*a + a there is no number divisible by a.
Knowing that and having input we enlarge our temp initialized with value of input by input. If it's in range [500, 1000] we enlarge our counter. Simple as that.
public static void main(String args[]) {
int count = 0;
int input = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number: ");
input = sc.nextInt();
while (input < 100 || input > 200) {
System.out.println("Enter number between 100 to 200");
input = sc.nextInt();
count++;
}
System.out.println(input + " fits " + count(input) + " times");
}
private static int count(int input) {
int result = 0;
int temp = input;
while (temp <= 1000) {
if (temp >= 500) {
result++;
}
temp += input;
}
return result;
}
According to your code, I see some issues. I'll point them out, as it is important for practicing Java.
Method can be either void or return int. You can't have void int. In this case, we return int, so int is the return type,
It's important to stick to Java styling. Don't put too many empty lines, keep indents.
Use Eclipse or IntelliJ (IntelliJ is more pro). They will point unused code blocks, so you would know that that getCount wasn't called.

I have been asked to make an Create a new integer array with 16 elements

Java code (not Java script). I was asked to create a new integer array with 16 elements.
Only integers between 1 and 7 are to be entered in the array from user (scanner)input.
Only valid user input should be permitted, and any integers entered outside the bounds (i.e. < 1 or > 7 should be excluded and a warning message displayed.
Design a program that will sort the array.
The program should display the contents of the sorted array.
The program should then display the numbers of occurrences of each number chosen by user input
however i have been trying to complete this code step by step and used my knowledge to help me but need help my current code is under I would appreciate if some one is able to edit my code into the above wants.I know it needs to enter the array by user input store and reuse the code to sort the numbers into sort the array.
The result should print out something like this like this
“The numbers entered into the array are:” 1, 2,4,5,7
“The number you chose to search for is” 7
“This occurs” 3 “times in the array”
import java.util.Scanner;
public class test20 {
public static void main (String[] args){
Scanner userInput = new Scanner (System.in);
int [] nums = {1,2,3,4,5,6,7,6,6,2,7,7,1,4,5,6};
int count = 0;
int input = 0;
boolean isNumber = false;
do {
System.out.println ("Enter a number to check in the array");
if (userInput.hasNextInt()){
input = userInput.nextInt();
System.out.println ("The number you chose to search for is " + input);
isNumber = true;
}else {
System.out.println ("Not a proper number");
}
for (int i = 0; i< nums.length; i++){
if (nums [i]==input){
count ++;
}
}
System.out.println("This occurs " + count + " times in the array");
}
while (!(isNumber));
}
private static String count(String string) {
return null;
}
}
import java.util.Scanner;
import java.util.Arrays;
public class test20 {
private static int readNumber(Scanner userInput) {
int nbr;
while (true) {
while(!userInput.hasNextInt()) {
System.out.println("Enter valid integer!");
userInput.next();
}
nbr = userInput.nextInt();
if (nbr >= 1 && nbr <= 7) {
return nbr;
} else {
System.out.println("Enter number in range 1 to 7!");
}
}
}
private static int count(int input, int[] nums) {
int count = 0;
for (int i = 0; i < nums.length; i++){
if (nums[i] == input){
count++;
} else if (nums[i] > input) {
break;
}
}
return count;
}
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
int[] nums = new int[16];
for (int i = 0; i < nums.length; i++) {
nums[i] = readNumber(userInput);
}
Arrays.sort(nums);
System.out.println ("Sorted numbers: " + Arrays.toString(nums));
int input = 0;
while(true) {
System.out.println("Search for a number in array");
input = readNumber(userInput);
System.out.println("The number you chose to search for is " + input);
System.out.println("This occurs " +
count(input, nums) + " times in the array");
}
}
}
Because the array is sorted, I break the loop if an element larger than the one we're looking for is found; if we encounter a larger one then no other matches can be found in the rest of the array.

Arrays with user input

I am trying to write a program that repeatedly asks the user to supply scores (out of 10) on a test.It needs to continue until a negative value is supplied. Values higher than 10 should be ignored. I also calculated the average of the inputs. After the scores have been inputted, i need to use a single array to produce a table that automatically fills the test scores and the number of occurrences of the certain test score.
I wanted it to look something like this:
Score | # of Occurrences
0 3
1 2
2 4
3 5
4 6
and so on.. P
I am a beginner and this is my first question, so i am sorry if i made a mistake in posting the question or something.
import java.io.*;
import java.util.*;
public class Tester1
{
public static void main()
{
Scanner kbReader= new Scanner (System.in);
int score[] = new int [10];//idk what im doing with these two arrays
int numofOcc []= new int [10];
int counter=0;
int sum=0;
for (int i=0;i<10;i++)// Instead of i<10... how would i make it so that it continues until a negative value is entered.
{
System.out.println("Enter score out of 10");
int input=kbReader.nextInt();
if (input>10)
{
System.out.println("Score must be out of 10");
}
else if (input<0)
{
System.out.println("Score must be out of 10");
break;
}
else
{
counter++;
sum+=input;
}
}
System.out.println("The mean score is " +(sum/counter));
}
}
You could use a do...while loop like this:
import java.io.*;
import java.util.*;
public class Tester1
{
public static void main(String args[]) {
Scanner kbReader= new Scanner (System.in);
int scores[] = new int [10];
int counter = 0;
int sum = 0;
int input = 0;
do {
System.out.println("Enter score out of 10 or negative to break.");
input=kbReader.nextInt();
if (input<0) {
break;
} else if (input>10) {
System.out.println("Score must be out of 10");
} else {
scores[input]++;
counter++;
sum+=input;
}
} while (input>0);
System.out.println("Score\t# of occur...");
for(int i =0; i<10; i++) {
System.out.println(i + "\t" + scores[i]);
};
System.out.println("The mean score is " +(sum/counter));
}
}
The formatting can certainly be done better (without c-style tabs) but I don't remember the syntax at the moment.
I think what you need is a List Array! Create ArrayList from array
Think of it as a dynamic array, you don't need to specify the size of the array and it is expanded/made smaller automatically.
What you're missing is a while loop. Here is a nice way to loop through a Scanner for input. It also catches numbers greater than 10 and provides an error message:
public static void main() {
Scanner s = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
int response = 0;
while (response >= 0) {
System.out.print("Enter score out of 10: ");
response = s.nextInt();
if (response > 10) {
System.out.println("Score must be out of 10.");
} else if (response >= 0) {
list.add(response);
}
}
// Do something with list
}

Categories

Resources