I have to implement a program using Stack which allows a user to enter a positive integer,n, followed by n integers. Then the program should allow the user to enter another integer, val after which the program should display the last value which is greater than val. From my understanding of the program, I figured out that it should compare each element from the top of the stack to the val. Therefore to compare each element to val, it should iterate through the values in the stack starting from the top. I don't really know how to make this work so would be pleased if I could get any help. Here is my program:
public class MyClass{
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
Stack<Integer> NumsInStack= new Stack<Integer>();
int n, num, val;
System.out.println("Please enter n.");
n=sc.nextInt();
for(int i=0; i<n;i++){
num=sc.nextInt();
NumsInStack.push(num);
}
System.out.println("Enter a value.");
val=sc.nextInt();
for(int i=0; i<NumsInStack.size();i++){
if(NumsInStack.peek()>val)
System.out.println("The number greater than "+val+" is "+NumsInStack.peek());
}
}
}
You should never iterate over a stack, it defeats the entire purpose of choosing that data structure. You want to use pop and peek:
while (!NumsInStack.empty()) {
if (NumsInStack.peek() > val) {
System.out.println("woot!");
break;
}
NumsInStack.pop();
}
Since you only want it to print out the last number that is higher, you should also put a break; after the print statement so that it breaks out of the loop when it finds a match. Without the break it would print all of the values that are higher.
Working code:
import java.util.*;
public class MyClass {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Stack<Integer> NumsInStack = new Stack<Integer>();
int n, num, val;
System.out.println("Please enter n.");
n = sc.nextInt();
for (int i = 0; i < n; i++) {
num = sc.nextInt();
NumsInStack.push(num);
}
System.out.println("Enter a value.");
val = sc.nextInt();
while ( !NumsInStack.empty()){
int stackElement = NumsInStack.pop();
if ( stackElement > val){
System.out.println("Stack Element > value :"+stackElement+":"+val);
break;
}
}
}
}
Related
Here is my program which is supposed to create an array and initialize prime numbers to it. The prime numbers should then be printed but the program just keeps running.
import java.util.*;
public class primes
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of primes ");
int x = scan.nextInt();
int[] prime = new int[x];
int div=2,hold=2;
int c=0;
while (prime[x-1]==0)
{
for(int a=2; div>a;a++)
{
if(div>a && div%a==0)
a=div;
else if(div==(a-1))
hold=div;
}
if(div==2||hold!=prime[c-1])
{
prime[c]=hold;
c++;
}
div++;
}
for(int f =0; f<x;f++)
System.out.print(" "+prime[f]+" ");
}
}
I tried changing my loops but I just don't know whats wrong
Like the others mentioned your logic is not right, try something like:
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of primes ");
int x = scan.nextInt();
List<Integer> primes = getPrimes(x);
Integer[] primeArray = primes.toArray(new Integer[primes.size()]);
for(int i :primes.toArray(primeArray)){ // you could just use for(int i :primes){ if you don't need array
System.out.print(i + " ");
}
}
private static List<Integer> getPrimes(int upperLimit) {
ArrayList primes = new ArrayList();
for (int i = 2; i < upperLimit; i++) {
boolean isPrime = true;
// Is it prime?
for (int j = 2; j < i; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime)
primes.add(i);
}
return primes;
}
The above will print out up to the numbers entered so if you type 5 it will print out 2 3 but not 5.
The following is an other example with Java 8, this one will print as many prime numbers based on the input, if you input 5 you will get 2 3 5 7 11
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of primes ");
int x = scan.nextInt();
long[] prime = primes(x).toArray();
Arrays.stream(prime).forEach(value -> System.out.print(value + " " ));
}
private static LongStream primes(long max) {
return LongStream.iterate(2, i -> i + 1)
.filter(PrimeNumber::isPrime)
.limit(max);
}
private static boolean isPrime(long x) {
return LongStream.rangeClosed(2, (long)(Math.sqrt(x)))
.allMatch(n -> x % n != 0);
}
Your code is wrong. First correct it, And i think you want to store prime numbers coming in range of 1 to N where N is user provided number. Use arrayList (growable) to store it.
It will keep on running because you have this: while (prime[x-1]==0). Where x is an input from the user. Say 5 for instance, then prime[5-1] initially is going to contain a 0 always, and you are running your while loop on this condition which is always going to turn true, thus never ending. Also, your prime number generation logic is not right!
I ran your code in debugger mode and I found the problem.
I tested your program with x=5.
At the end of the first while loop iteration you have :
prime[0] = 2
div = 3
hold = 2
c = 1
And here's the problem :
if(div==2||hold!=prime[c-1])
{
prime[c]=hold;
c++;
}
This part won't ever be reached anymore because :
div is never decrement, so it will always be superior to 2.
hold is
equal to prime[c-1], and never change value.
So prime will always stick to be : 2 0 0 0 0, and your while loop will never end.
I found what was wrong and rewrote the code, it works now. The program asks the user for the number primes they want to see and it prints them after storing them in a basic integer array.
import java.util.*;
public class Prime
{
public static void main(String [] args)
{
Scanner scan= new Scanner(System.in);
int i=0, hold=2, d=2;
boolean flag = true;
System.out.println("Enter the number of primes.");
int[] prime= new int[scan.nextInt()];
for(;flag;){
for(int a=2;d>a;a++){
if(d==(a)||d%a==0){
break;
}
if((d-1)==a){
hold = d;
}
}
d++;
if(hold==2 || hold!=prime[i-1]){
prime[i] = hold;
i++;
}
if(i==prime.length)
flag= false;
}
for(int x=0;x<prime.length;x++)
System.out.print(prime[x]+" ");
System.out.println("");
}
}
I am writing a program which allows the user to enter a list of positive integers(terminated by a 0) in a stack and displays them in reverse order. I am first trying to print out the elements of the stack to test it first but the program is not printing out the elements when I enter 0.
Here is my program:
import java.util.*;
public class MyClass{
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
Stack<Integer> addToStack= new Stack<Integer>();
int num;
System.out.println("Enter the a list of positive integers. Terminate with a 0.");
num= sc.nextInt();
while(num!=0){
addToStack.push(num);
}
System.out.println("Displaying numbers from the stack "+ addToStack);
}
}
You weren't control your entered number in loop.
Change your while condition with these while ((num = sc.nextInt()) != 0) {
And the result is now :
Enter the a list of positive integers. Terminate with a 0.
1
2
0
Displaying numbers from the stack [1, 2]
Taking user inputs
You can use an infinite loop to take user input and break the loop when input is 0.
Sorting user inputs
When you needs to sort the input according to the reverse order. So you you can use default java collection sorting method Collections.sort(List,Compartor) which is provided in Collections class.
Use following code.
class MyClass {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Stack<Integer> addToStack = new Stack<Integer>();
int num;
do {
System.out.print("Enter the a list of positive integers. Terminate with a 0.");
num = sc.nextInt();
addToStack.push(num);
} while (num != 0);
//sort reverse order
Collections.sort(addToStack, Collections.reverseOrder());
System.out.print(addToStack);
}
}
You have an infinite loop. You have to re-ask the user for a new Integer, otherwise you will keep looping indefinetily
while(num!=0){
addToStack.push(num);
num= sc.nextInt();
}
Your code will run infinitely.You have to write num= sc.nextInt(); inside the loop.
e.g:
while(num!=0){
addToStack.push(num);
num= sc.nextInt();
}
• Ask the user to enter a set of 5 numbers.
• For each number entered, add it into the front of the linked list.
• Now, ask the user to enter a search number.
• Using a for loop or while loop, search whether the number exist in one of the Nodes in the linked list.
• If there is a matching node, create a new node with data 88 and insert it right before the matching node. Otherwise, display the message “No such number”.
Hi everyone, I would like you to help me with the java code for the last part.
public static void main(String[] args) {
LinkedList list = new LinkedList();
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
int num = sc.nextInt(); sc.nextLine();
for(int i = 0; i < 4; i++){
list.addFront(num);
}
System.out.print("Enter a number: ");
int search = sc.nextInt(); sc.nextLine();
for(Node j = list.getHead(); j!= null; j=j.getNext()){
if((Integer)j.getData()==search){
list.addNode();
}else{
System.out.println("No such number");
}
}
public static Node addNode(T n);//???
}
I think your code will not even work for the first point. What you do is read a number once and then put the same number 4 times into the linked list.
For adding the node to the list before another node you need the index of the node where you want to put it in front of and then use the add(int index, E element) mehtod of the LinkedList. The index can be found by indexOf(Object o).
https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html
Re factored your code.Here is a working solution.You don't need to create an additional function for addNode().
There is a predefined function known as add(index,element) when you are using java.util.LinkedList.But i would advice to first create your own linklist instead of using predefined LinkedList class.
This will clear all your doubts.
Here i am assumming you are using java.util.LinkedList.
public static void main(String args[]){
LinkedList<Integer> list = new LinkedList<Integer>();
Scanner sc = new Scanner(System.in);
for(int i = 0; i < 4; i++)
{
System.out.println("Enter a number: ");
int num = sc.nextInt(); sc.nextLine();
list.addFirst(num);
}
System.out.print("Initial list:"+list);
System.out.print("Enter a number: ");
int search = sc.nextInt(); sc.nextLine();
Iterator<Integer > itr=list.iterator();
int i=0;
boolean flag=false;
while(itr.hasNext())
{
int data=itr.next();
if(data==search){
list.add(i,88);
flag=true;
break;
}
i++; //index of data
}
if(!flag)
{
System.out.println("No such number");
}
else
{
System.out.println("Number inserted at "+i);
}
System.out.print("final list:"+list);
sc.close();
}
Hope it helps you.
I am writing a program that would help me find whether the number entered is a palindrome or not but i am trying it using arrays. And i would like to know if that is even possible?? And if it is possible then what am i doing wrong.
I have marked the code where i think the problem lies but feel free to suggest anything.!!!!
Thanks!!!
import java.util.Scanner;
public class palindrome
{
public static void main(String args[])
{
int size = 10,i,j,flag=0;
int num[] = new int[size];
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the number ");
size = sc.nextInt();
System.out.println("Enter the number ");
for(i=0;i<size;i++)
{
num[i]=sc.nextInt();
}
i=size-1;
for(j=0;j<(size/2);j++,i--)
{
if(i>(size/2))
{
if(num[i]==num[j])
{
flag = 1;
}
}
}
if(flag==1)
{
System.out.println("The number is a palindrome");
}
else
System.out.println("The number is not a palindrome ");
}
}
Edit: Guys the problem is actually solved because i was doing a blunder mistake i.e. i was asking the user to enter the number in the form of an arry but i was not actually entering the digits in the number one by one instead i was entering the whole number in the first iteration.
But still a lot of thanks for the replies. I would still try your ideas and let you guys know. Thanks
:)
Try
public boolean isPalindrome(int[] num){
for(int i = 0 ; i < num.length/2 ; i++) {
if(num[i]!=num[num.length-(i+1)]) return false;
}
return true;
}
Yes it's possible, moreover, it's possible by using ArrayList, String - whatever you like. In order to write down a correct implementation, first decompose your current solution:
// Extract a method, do not cram all code into main()
// note: all you need is array, to get size of the array, put value.length
private static boolean isPalindrome(int[] value) {
...
}
public static void main(String args[]) {
int userInput[];
...
if (isPalindrome(userInput)) {
System.out.println("The number is a palindrome");
}
else {
System.out.println("The number is not a palindrome");
}
}
Now, let's implement isPalindrome():
private static boolean isPalindrome(int[] value) {
if (null == value)
return true; //TODO: or false, or throw exception
for (int i = 0; i < value.length / 2; ++i)
if (value[i] != value[value.length - 1 - i])
return false;
return true;
}
The easiest and most intuitive way (imo) to check for palindromes is through recursion. The idea is simple:
Is the first and last char the same?
YES Remove first and last char and check first and last char of the new String
NO There is no palindrome.
When the input is only 1 char then it's trivial.
Have a look at this code:
private void isPalindrome(String number){
if(number.length() == 1){
System.out.println("yes");
}else if(number.charAt(0) == number.charAt(number.length()-1)){
isPalindrome(number.substring(1, number.length()-1));
}else{
System.out.println("no");
}
}
Testing with:
isPalindrome(String.valueOf(232)) Returns "yes"
isPalindrome(String.valueOf(23)) Return "no"
Of course this also works with Arrays just as easily. Replace the parameter with an array and search through the indices the same way. When cutting down the array just create a new smaller array without first and last index of the previous array.
Your class has several issues:
First you're not checking if a number is a palindrome or not. Your algorithm is flawed
Second, you're asking to enter a size but in the end, the user inputs it but you don't use it yourself. Instead, you're using that introduced value in the number array.
Here's how you should do it.
public class Palindrome {
private static boolean isPalindrome(int[] array) {
for (int i = 0, j = array.length-1; i < j; i++, j--) {
if (array[i] != array[j]) {
return false;
}
}
return true;
}
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.print("How many numbers do you want to enter? ");
int size = scanner.nextInt();
int[] numbers = new int[size];
for (int i = 0; i < size; i++) {
System.out.printf("Enter number %s: ", i+1);
numbers[i] = scanner.nextInt();
}
if (isPalindrome(numbers)) {
System.out.println("The number is a palindrome");
} else {
System.out.println("The number is not a palindrome");
}
}
}
I am trying to write code to have users input positive integers and have them sent to a linked list. The users input should end after entering a negative number. Furthermore, I am having issues writing an isSorted boolean method that will return true if the linked list is sorted in increasing order and false otherwise.
Here is the only code I have so far
import java.util.*;
public class List {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please type positive integers one by one separated by a space.");
System.out.println("When you are done, please type a negative integer.");
int num = input.nextInt();
}
public boolean isSorted(){
if(){
return true;
}
else{
return false;
}
}
}
public void input() {
System.out.println("Please type positive integers one by one separated by a space.");
System.out.println("When you are done, please type a negative integer.");
LinkedList<Integer> ll = new LinkedList<>();
//System.in.available()
Scanner input = new Scanner(System.in);
int num;
while ( input.hasNextInt() ) {
int i = input.nextInt();
if (i >= 0) {
ll.add(i);
}
}
System.out.println(ll+" <-- ll"); //TODO remove debugging code
System.out.println(isSortedAccending(ll)+" <-- isSortedAccending(ll)");//TODO
}
This works by returning false the moment something is found out of order.
public static boolean isSortedAccending(List<Integer> list){
if (list.size() < 2) {
return true;
}
Integer previous = list.get(0);
for (Integer next : list) {
if (previous > next) {
return false;
}
}
return true;
}
Outputs:
Please type positive integers one by one separated by a space.
When you are done, please type a negative integer.
1
2
3
-1
[1, 2, 3] <-- ll
true <-- isSortedAccending(ll)
isSortedDecending() looks exactly the same except it uses <.
import java.util.LinkedList;
import java.util.Scanner;
public class NumberListing {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please type positive integers one by one separated by a space.");
System.out.println("When you are done, please type a negative integer.");
int num = input.nextInt();
LinkedList<Integer> list = new LinkedList<Integer>();
while(num > 0){
list.add(num);
num = input.nextInt();
}
if(isSorted(list)){
System.out.println("The list is sorted");
} else{
System.out.println("The list is not sorted");
}
}
public static boolean isSorted(LinkedList<Integer> list){
boolean done = false;
boolean sorted = true;
for(int i = 1; i < list.size() && !done ; i++){
if(list.get(i) < list.get(i-1)){
done = true;
sorted = false;
}
}
return sorted;
}
}
Should be fairly simple. While the number you intake is greater than 0, store the number in a list and get the next one from the console.
After that, loop through the list starting with index 1 to check that each current number is greater than the previous number. I added an early exit so the loop quits anytime a number that is less than the previous number. this means it is unordered and we don't care about the rest.
However, if you're trying to create your own linked list that creates a lot more code and I would suggest looking in a text book or something of the sort to help.
You can put your int's in a container(LinkedList) by using the wrapper class Integer for int. The normal int is a standard primitive type and can not be used by containers, as containers can only work with objects of a class.
LinkedList<Integer> list = new LinkedList();
As for the isSorted method, you could iterate through the list and check if the current value is higher or equal to the previous value.
int prevValue = 0;
for(int i = 0; i < list.size(); i++){
if(!list.get(i) >= prevValue){
return false;
}
prevValue = list.get(i);
}
return true;
You'll want to read the next line as a String, split that line, and walk through the list of elements of that line, adding the positive elements to a LinkedList as you go. Make sure you store your scanner. You'll want to use nextLine, not nextInt.
import java.util.*;
public class List {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please type positive integers one by one separated by a space.");
System.out.println("When you are done, please type a negative integer.");
String line = input.nextLine();
String[] integers = line.split(" ");
LinkedList ll = new LinkedList<Integer>();
for (int i = 0; i < integers.length; i++)
{
if (Integer.parseInt(integers[i]) > 0)
ll.add(integers[i]);
}
System.out.println(isSorted(ll));
input.close();
}
Then, just use a simple comparison function for LinkedList to check if it's sorted:
public static <T extends Comparable<T>> boolean isSorted(LinkedList<T> iterable)
{
Iterator<T> iter = iterable.iterator();
if (!iter.hasNext()) {
return true;
}
T t = iter.next();
while (iter.hasNext()) {
T t2 = iter.next();
if (t.compareTo(t2) > 0) {
return false;
}
t = t2;
}
return true;
}