(ALL IN JAVA) Given a stack of integers , how would you check to see whether the
ID: 672484 • Letter: #
Question
(ALL IN JAVA)
Given a stack of integers , how would you check to see whether the product of each succesive pair of numbers in the stack is greater than the sum of the next pair or not. If the stack has an odd number of elements, the element at the top is left out of a pair.For example, if the stack of elements are (bottom to top)[10,5,2,21,6,5,3,-7,-3],then the output should be true because the productsof each of the pairs[10,5][2,21][6,5] and [3,-7] come out to 55>42>30>-21.
Check for any special cases and the method must return a boolean.
Explanation / Answer
Please find the program followed by the test result:
import java.util.*;
import java.lang.*;
import java.io.*;
public class HelloWorld{
public static void main (String[] args) throws java.lang.Exception
{
boolean bresult=true;
//int[] istack;
int count,i,cntr,j;
String str;
System.out.println("Program to check to see whether the product of each succesive pair of numbers in the stack is greater than the product of the next pair or not: ");
Scanner in = new Scanner(System.in);
System.out.println("Please enter stack of integers separated by ,: ");
str=in.nextLine();
while (str.length() ==0){
System.out.println(" ERROR - List is empty. ");
System.out.println("Please enter stack of integers: ");
str=in.nextLine();
}
String words[]=str.split(",");
count=words.length;
System.out.println();
//System.out.println("Your string has "+ count +" words in it.");
//int istack[count];
int istack[] = new int[count];
for (i=0; i<count; i++){
istack[i] = Integer.parseInt(words[i]);
//System.out.println("stack"+i+" "+istack[i]);
}
if (count % 2 ==0) cntr=count;
else cntr=count-1;
//System.out.println("cntr ="+cntr);
if (cntr>2){
int pstack[] = new int[cntr/2];
//for (j=0; j<cntr ; j++){
for (i=0; i<(cntr/2); i++){
//for (j=0; j<cntr ; j++){
pstack[i]=istack[i*2]*istack[i*2+1];
//System.out.println("i is "+i+" "+pstack[i]);
}
bresult=true;
for (i=1; i<(cntr/2); i++){
if (pstack[i-1]<=pstack[i]){
bresult=false;
//System.out.println("i "+i+" "+pstack[i-1]+" "+pstack[i]);
break;
}
}
}
else if (cntr<=2) bresult=true;
System.out.println("Result is "+bresult);
}
}
Test Result:
sh-4.3$ javac HelloWorld.java
sh-4.3$ java -Xmx128M -Xms16M HelloWorld
Program to check to see whether the product of each succesive pair of numbers in the stack is greater than the product of the next pair or not:
Please enter stack of integers separated by ,:
10,5,2,21,6,5,3,-7,-3
Result is true
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.