What is wrong with the logic of following code? - java

The following code gives only two outputs (2 and 3), after this it gets terminated, why doesn't it continue?
public class PrimeSeries {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
boolean prime = true;
for(int i=2;i<=N;i++) {
for(int j=2;j*j<=i;j++) {
if(i%j == 0) {
prime = false;
break;
}
}
if(prime == true) {
System.out.println(i);
}
}
}
}

The code you provided doesn't work because you never made the variable boolean prime true again
So just make the boolean back to true again after every iteration of the inner for loop.
public class PrimeSeries {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
boolean prime = true;
for(int i=2;i<=N;i++) {
// ADD THIS LINE
prime = true;
for(int j=2;j*j<=i;j++) {
if(i%j == 0) {
prime = false;
break;
}
}
if(prime == true) {
System.out.println(i);
}
}
}
}
That is it! 😁

Related

Given a A string , print Yes if it is a palindrome, print No otherwise

I want to check if the user input is a palindrome or not. But this is not working as expected. Please help.
The code I tried:
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String A=sc.next();
for (int i=0; i<A.length()/2; i++){
if(A.charAt(i)==A.charAt(A.length()-i-1)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
}
}
You're printing "Yes" for every character that has the same character at the opposite end of the String and "No" if not. Modify your loop to return a boolean that tells whether the String is a palindrome or not and then print it at the end like so:
boolean isPalindrome = true;
for (int i=0; i<A.length()/2; i++){
if(!A.charAt(i)==A.charAt(A.length()-i-1)){
isPalindrome = false;
}
}
if(isPalindome){
System.out.println("Yes");
} else {
System.out.println("No");
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String A = sc.next();
String reverse = new StringBuffer(A).reverse().toString();
if (A.equals(reverse))
System.out.println("Yes");
else
System.out.println("No");
}
int end = A.length()-1;
int i=0;
boolean isPol = true;
while (i<=end){
if (A.charAt(i)!=A.charAt(end))
isPol = false;
i++;
end--;
}
if (isPol == true) System.out.println("Yes");
else System.out.println("No");
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String A = sc.next();
/* Enter your code here. Print output to STDOUT. */
String reverse = "";
int length = A.length();
for (int i=length-1;i>=0;i--){
reverse = reverse + A.charAt(i);
}
boolean ans = A.equals(reverse);
if (ans) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
}
Scanner sc = new Scanner(System.in);
String A = sc.next();
boolean isPalindrome = false;
int len = A.length();
if(len > 1) {
for (int i = 0; i < len/2; i++) {
if (A.charAt(i) == A.charAt(len-i-1)) {
isPalindrome = true;
}else {
break;
}
}
}else if (len <= 1) {
isPalindrome = true;
}
if (isPalindrome) {
System.out.println("Yes");
}else {
System.out.println("No");
}
sc.close();
import java.util.Scanner;
public class test {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
String A=sc.nextLine();
String temp="";
for(int i=A.length()-1;i>=0;i--){
temp = temp + A.charAt(i);
}
if(A.equals(temp)){
System.out.println("Yes");
}else{
System.out.println("No");
}
}
}

Using stack to check equal number of letters and digits in password

I have to write a program to check a password whereby the password should
should be at least 8 characters long
contain only letters and digits(special characters)
contain an equal number of letters and digits
The program should check if it is valid and displays an appropriate message.
Also, only the stack class should be used as the data structure.
Here is what I have come up with so far:
public class dsa_1c {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc= new Scanner(System.in);
String pass;
System.out.println("Enter a password");
pass= sc.nextLine();
if(checkPass(pass)){
System.out.println("Valid Password");
}
else{
System.out.println("Invalid Password");
}
}
public static boolean checkPass(String password){
Stack<Character> stack= new Stack<Character>();
int count1=0, count2=0;
if(password.length()<8){
return false;
}
else{
for(int i=0; i<password.length();i++){
char c= password.charAt(i);
if (!Character.isLetterOrDigit(c)){
return false;}
if(Character.isLetterOrDigit(c)){
stack.push(c);
}
char top= stack.peek();
if(Character.isLetter(top)){
count1++;
stack.pop();
}
else if(Character.isDigit(top)){
count2++;
stack.pop();
}
if(count1==count2){
return true;
}
if(!stack.isEmpty()){
return false;
}
}
}
return true;
}
}
The program when run displays "Valid Password" for any password I type in with more than 8 characters and with no special characters.
It's this part which is apparently the issue
if(count1==count2){
return true;}
because when I change it
if(count1!=count2)
return false; }
it returns Invalid Password for any valid ones.
It's return true in the end that causes an issue. Instead of comparing two counts and returning the values, you can just use return count1 == count2;. Below is an example:
public static boolean checkPass(String password) {
Stack<Character> stack = new Stack<Character>();
int count1 = 0, count2 = 0;
if (password.length() < 8) {
return false;
} else {
for (int i = 0; i < password.length(); i++) {
char c = password.charAt(i);
if (!Character.isLetterOrDigit(c)) {
return false;
} else {
stack.push(c);
}
}
while(!stack.isEmpty()){
char c = stack.pop();
if(Character.isLetter(c)){
count1++;
}else{
count2++;
}
}
return count1 == count2;
}
}
Using a stack seems like overkill to me - it's enough to iterate over the characters, count the digits and the letters, and make sure they have the same number:
private static boolean isValidPassword(String password) {
int letterCount = 0;
int digitCount = ;
for (int i = 0; i < password.length(); ++i) {
char c = password.charAt(i);
if (Character.isLetter(c)) {
++letterCount;
} else if (Character.isDigit(c)) {
++digitCount;
} else {
return false;
}
}
return (letterCount + digitCount) >= 8 &&
letterCount == digitCount;
}
Assuming this is an exercise just to manipulate a stack, here is my 2 cents:
public class dsa_1c {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a password");
String pass = sc.nextLine();
if (checkPass(pass)) {
System.out.println("Valid Password");
} else {
System.out.println("Invalid Password");
}
}
private static boolean checkPass(String pass) {
boolean result = false;
if (pass.length() == 8) {
Stack stack = new Stack();
for (char current : pass.toCharArray()) {
if (stack.isEmpty()) {
stack.push(current);
continue;
}
char previousChar = stack.pop();
if (sameType(current, previousChar)) {
stack.push(previousChar);
stack.push(current);
}
}
if (stack.isEmpty()) {
result = true;
}
}
return result;
}
public static boolean sameType(char current, char previousChar) {
boolean result = false;
if (Character.isAlphabetic(current) && Character.isAlphabetic(previousChar)) {
result = true;
}
else if (Character.isDigit(current) && Character.isDigit(previousChar)) {
result = true;
}
return result;
}
static class Stack extends ArrayList {
public static final char NULL_CHARACTER = 0x0;
public void push(Character letter) {
add(letter);
}
public Character pop() {
Character result = NULL_CHARACTER;
if (!isEmpty()) {
result = (Character)remove(size()-1);
}
return result;
}
}
}

I get "Exception in thread "main" java.util.NoSuchElementException" when i execute my program

I'm making an assignment for my study, but everytime i execute my program I get an error. The error is "Exception in thread "main" java.util.NoSuchElementException".
I have no clue how to fix this, can anyone help me?
This is my program:
import java.util.Scanner;
class Cellulitis {
Scanner sc = new Scanner(System.in);
static char automata;//type A or B automaton
static int length; //length of row
static int gen; //generation
static boolean[] cellrow;
static boolean[] newCellrow;
void readGeneral() {//define different variables
automata = sc.next().charAt(0);
length = sc.nextInt() + 2;
gen = sc.nextInt();
cellrow = new boolean[length];
newCellrow = new boolean[length];
}
void readInitialConfiguration() {//input initial configuration
sc.next();
while (sc.hasNextInt()) {
cellrow[sc.nextInt()] = true;
}
}
void draw() {//prints out each cellrow
for(int i = 0; i < length-1; i++) {
if(cellrow[i]){
System.out.print('*');
}
else{
System.out.print(' ');
}
}
System.out.println("");
}
boolean newCellValueByA(int k){//calculates the state of each cell by the last cellrow by rules of automaton A
if (cellrow[k]) {
if((!cellrow[k-1] && cellrow[k+1]) || (cellrow[k-1] && !cellrow[k+1])){
return true;
}
else{
return false;
}
}
else{
if(!cellrow[k-1] && !cellrow[k+1]){
return false;
}
else{
return true;
}
}
}
boolean newCellValueByB(int k){//claculates the state of each cell by the last cellrow by rules of automaton B
if(cellrow[k]) {
if(!cellrow[k+1]){
return true;
}
else{
return false;
}
}
else{
if((!cellrow[k-1] && cellrow[k+1]) || (cellrow[k-1] && !cellrow[k+1])){
return true;
}
else{
return false;
}
}
}
void changeToNewRow() {//selects what rule will be used and makes the new cellrow
for(int i = 1; i < length - 1; i++){
if(automata == 'A'){
newCellrow[i] = newCellValueByA(i);
}
else if(automata == 'B'){
newCellrow[i] = newCellValueByB(i);
}
}
cellrow = newCellrow.clone();
}
void nextCellrow() {//draws the cellrow and jumps to the next cellrow
for(int i = 1; i < gen; i++){
draw();
changeToNewRow();
}
}
public static void main(String[] args) {
(new Cellulitis()).readGeneral();
(new Cellulitis()).readInitialConfiguration();
(new Cellulitis()).draw();
(new Cellulitis()).changeToNewRow();
(new Cellulitis()).nextCellrow();
}
}
This is the error i get:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1416)
at Cellulitis.readInitialConfiguration(Cellulitis.java:28)
at Cellulitis.main(Cellulitis.java:108)
How can i fix this?
Thanks in advance!
As seen together in the answers, problem was because
Scanner sc = new Scanner(System.in);
had to be changed to
private static Scanner sc = new Scanner(System.in);

Recursive method to add odd numbers

I have the below snippet of code to use a recursive method to add the sum of odd numbers.
I have already coded the iterative method successfully that adds the sum of all odd numbers between n and m which are entered by the user. I'd like to reach that goal but am started slow to make sure I understand what is happening.
I know that it makes more sense to do it iteratively, however I am experimenting with the two types to see which is more efficient. I am stuck on the below as it is not doing what i want it to and i can't understand why.
import java.util.*;
public class SumofOdd
{
public static void main (String [] args)
{
int n = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter an odd number");
n = sc.nextInt();
int x = add(n);
}
public static int add(int x)
{
if (x == 0)
{
return 0;
}
else
{
return (x + add(x-1));
}
}
}
I have changed the above to the below. It compiles however stops after I enter the number.
import java.util.*;
public class SumofOdd
{
public static void main (String [] args)
{
int n = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter an odd number");
n = sc.nextInt();
if (n%2 == 0)
{
System.out.println("The number entered is even");
}
else
{
int x = add(n);
}
}
public static int add(int x)
{
if (x <= 0)
{
return 0;
}
else
{
return (x + add(x-2));
}
}
}
import java.util.*;
public class OddR{
public static void main (String Args [])
{
Scanner s = new Scanner(System.in);
System.out.println("Enter an odd number");
int max = s.nextInt();
if((max% 2) == 0) {
System.out.println(max + " is Even number and therefore is invalid");
}
else{
System.out.println("Enter a greater odd number");
int m = s.nextInt();
if (m <max){
System.out.println("Invalid data");
}
else{
if((m % 2) == 0) {
System.out.println(m + " is Even number and therefore is invalid");
}
else{
int data = (addodd(m)- addodd(max))+max;
System.out.print("sum:"+data);
}
}
}
}
public static int addodd(int m)
{
if(m<=0)
{
return 0;
}
if(m%2 != 0)
{
return (m+addodd(m-1));
}
else
{
return addodd(m-1);
}
}
}
This is the answer recursively of the sum of odd numbers from n to m
public int addOdds(int n) {
if (n <= 0) {
return 0;
}
if (n % 2 == 0) {
return addOdds(n - 1);
}
return x + addOdds(n - 1);
}
Take care, I never tested the code.
class Oddsum {
public int addodd(int n)
{
if(n<=0)
{
return 0;
}
if(n%2 != 0)
{
return (n+addodd(n-1));
}
else
{
return addodd(n-1);
}
}
}
public class Xyz {
public static void main (String[] v)
{
int n = 9;
Oddsum o = new Oddsum();
int data = o.addodd(n);
System.out.print("sum:"+data);
}
}
This is working fine
public static void main (String[] args){
public static int oddSum(int s){
if (s <= 0)
return 0;
else
return s + oddSum(s -2);
}
}

Simple Java Method Error when Returning

I'm learning methods and was trying to write code that basically tells if a number is prime. However, I keep encountering the error:
error: cannot find symbol
return(isPrime);
^
error: illegal start of type
return(isPrime);
This is my current code (i hope i'm using the method correctly):
import java.util.Scanner;
public class DoublePalindromicPrimes{
public static void main(String args[]){
Scanner in= new Scanner(System.in);
System.out.println("Please enter a number:");
int n = in.nextInt();
//prime(n);
boolean resultPrime = prime(n);
if (resultPrime){
System.out.println("This is a prime");
}
else {
System.out.println("This is not a prime");
}
}
public static boolean prime(int x){
for (int i=2;i<x;i++){
boolean isPrime;
if (x%i==0){
isPrime=false;
}
else{
isPrime=true;
}
}
return isPrime;
}
}
Any help is appreciated!
public static boolean isPrime(int x)
{
if(x > 2) {
if(x%2 == 0) {
return false;
} else {
int sqrt = (int)(Math.sqrt(x));
for(int i=3;i<=sqrt;i+=2) {
if(x%i == 0) {
return false;
}
}
}
return true;
} else if(x==2) {
return true;
} else { //1, 0, and negatives
return false;
}
}
change it to
return isPrime;
note the space and make declaration out of isPrime for loop
You declared isPrime inside your loop, so the return statement can't see it. Move it outside the loop.
public static boolean prime(int x) //throws InvalidNumberException
{
if (x <= 0)
{
//throw new InvalidNumberException("The number is invalid");
}
int squareRoot = (int)(Math.sqrt(x));
for (int i = 2; i <= squareRoot; i++)
{
if (x % i == 0)
{
return false;
}
}
return true;
}
This is an optimized prime validator.

Categories

Resources