Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
The below code is for reversing a 3 digit number and then checking while they are equal.
Main method
public class Main {
public static void main(String[] args) {
boolean result= NumberPalindrome.isPalindrome(121);
System.out.println(result);
}
}
Method for reversing number
public class NumberPalindrome {
public static boolean isPalindrome(int number){
int reserve=100;
int reverseNumber=0;
while (number>0){
int lastDigit=(number%10);
reverseNumber+=(lastDigit*reserve);
reserve/=10;
number/=10;
}
System.out.println("reverse number"+reverseNumber);
if (reverseNumber==number){
return true;
}else {
return false;
}
}
}
I have given a print statement right after the while loop ends and that print gives correct expected value but the if statement gives false even when it has to be true.
You are changing number before if ,
just assign it to another value then check it .
public class NumberPalindrome {
public static boolean isPalindrome(int number){
int my_num = number;
.
.
.
if (reverseNumber==my_num){
...
number/=10; //this is where number is changing
public static boolean isPalindrome(int input) {
int reserve = 100;
int reverseNumber = 0;
int number = input;
while (number > 0) {
int lastDigit = (number % 10);
reverseNumber += (lastDigit * reserve);
reserve /= 10;
number /= 10;
}
System.out.println("reverse number" + reverseNumber);
System.out.println("original number" + input);
return reverseNumber == input;
}
Because you modified your input param number in number /= 10
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
import java.util.*;
public class Fact
program to find factorial numbers
{
Scanner sc=new Scanner(System.in);
int n;
Fact()
an empty constructor
{
}
void accept()
{
System.out.println("Enter the number");
n=sc.nextInt();
System.out.println(pact(n));
}
**int pact(int n)**
here is where my program says that it is missing a semicolon
(
if(n==1)
return 1;
else
return n*fact(n-1);
}
public static void main()
{
Fact obj=new Fact();
obj.accept();
}
}
Apart from the fact that
int pact(int n)
(
should be
int pact(int n)
{
You have String args[] missing as the arguments in the main method.
public static void main(String[] args){
After return statement you used closed curly, and no open curly is there .
You started with open parenthesis and closed with curly.
Just change that.
Try this. Removed invalid language constructs.
import java.util.Scanner;
public class Fact {
Scanner sc = new Scanner(System.in);
int n;
Fact() {
}
void accept() {
System.out.println("Enter the number");
n = sc.nextInt();
System.out.println(fact(n));
}
int fact(int n) {
if (n == 1)
return 1;
else
return n * fact(n - 1);
}
public static void main(String[] args) {
Fact obj = new Fact();
obj.accept();
}
}
If you copied the code correctly, you need to use a { instead of ( in this part of the code.
(
if(n==1)
return 1;
else
return n*fact(n-1);
}
so it should be
{
if(n==1)
return 1;
else
return n*fact(n-1);
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm trying to print out the sum of each individual number in a number but it is not giving the correct answer. What is wrong with my code?
import javax.swing.*;
public class Tallist {
public static void main(String[]args) {
int sum = 0;
String tal = JOptionPane.showInputDialog(null, "skriv ett tal");
for(int X = 0; X<=15; X++) {
sum += tal.charAt(X);
System.out.println(sum);
}
}
}
First of all, if you want to iterate through the entire string, you should not fix the number of iterations to 15 in your for-loop.
for(int X = 0; X<=15; X++)
Could be written as:
for(int x=0; x<tal.length(); x++) //user lower case for non-final variables
Next, you are summing up the ASCII value of the input string, not the numbers.
So if "123" was input into the InputDialog, you are summing up ASCII for 123: (49 + 50 + 51) instead of adding up (1+2+3).
Just convert it to integers before summing up:
sum += Character.getNumericValue(tal.charAt(x));
If I understood you correctly you want to calculate the crossfoot of a number.
Here the code you need with user input via input dialog:
public class Crossfoot
{
public static void main(String[] args)
{
while (true)
{
String userInput = JOptionPane.showInputDialog("Enter number:");
if (!isInteger(userInput))
{
continue;
}
int crossfoot = 0;
for (int i = 0; i < userInput.length(); i++)
{
crossfoot += Character.getNumericValue(userInput.charAt(i));
}
System.out.println(crossfoot);
}
}
public static boolean isInteger(String string)
{
try
{
Integer.parseInt(string);
return true;
} catch (NumberFormatException numberFormatException)
{
return false;
}
}
}
As another user already wrote, you should iterate over the whole string and be careful with the ASCII values of the characters.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
public static void main(String args[]){
Scanner sc = new Scanner(System.in) ;
System.out.print("Enter String: ");
String str = sc.nextLine();
int n=str.length();
int count=0;
char[] strArray = str.toCharArray();
for(int i=0;i<n;i++)
{
if(isPrime(strArray[i]))
{
count=count+strArray[i];
}
}
System.out.println (count);
}
private static boolean isPrime(int num)
{
if(num==1 ||(num!=2 && num%2==0))
{
return false;
}
else
{
for(int i=2;i<num/2;i++)
{
if(num%i==0)
return false;
}
}
return true;
}
I'm converting string to character array to check for prime and calling the function
It's not giving the correct output.
Input:
123
Output:
5
I'm not getting the error here. what's the error in this code?
When you pass strArray[i] to isPrime, if you are passing '3', you are not checking if the number 3 is prime, you are checking if the numeric value of the character '3' is prime.
Assuming your input contains only digits, try to change the code to :
for(int i=0;i<n;i++)
{
if(isPrime(strArray[i]-'0'))
{
count=count+strArray[i]-'0';
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Anybody know how to identify a given number is odd/even using addition or subtraction operator? I am new to coding and don't have an idea how to do this?
using subtraction.
int inputNumber = 12;
while(inputNumber>2)
{
inputNumber-=2;
}
if(inputNumber==1)
System.out.println("Odd Number");
else
System.out.println("Even Number");
using addition
int inputNumber = 12;
int absInputNumber = Math.abs(inputNumber)
int i = 0;
while(i < absInputNumber) {
i += 2
}
if(inputNumber==i)
System.out.println("Even Number");
else
System.out.println("Odd Number");
Java answer (without reference to Math class):
package odd.even.tester;
public class OddEvenTester {
public boolean isEven(int number) {
int evaluatedValue = number;
if (evaluatedValue < 0) {
evaluatedValue *= (-1);
}
while (evaluatedValue > 0) {
evaluatedValue -= 2;
}
return evaluatedValue == 0;
}
}
short test:
package odd.even.tester;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
public class OddEvenTesterTest {
#Test
public void testIsEven() {
OddEvenTester tester = new OddEvenTester();
assertTrue(tester.isEven(-10));
assertTrue(tester.isEven(-8));
assertTrue(tester.isEven(-6));
assertTrue(tester.isEven(-4));
assertTrue(tester.isEven(-2));
assertTrue(tester.isEven(0));
assertTrue(tester.isEven(2));
assertTrue(tester.isEven(4));
assertTrue(tester.isEven(6));
assertTrue(tester.isEven(8));
assertTrue(tester.isEven(10));
assertFalse(tester.isEven(-9));
assertFalse(tester.isEven(-7));
assertFalse(tester.isEven(-5));
assertFalse(tester.isEven(-3));
assertFalse(tester.isEven(-1));
assertFalse(tester.isEven(1));
assertFalse(tester.isEven(3));
assertFalse(tester.isEven(5));
assertFalse(tester.isEven(7));
assertFalse(tester.isEven(9));
}
}
There is another way to do it using "mod" which is the '%' symbol. If you have a number and use % 2, then if the answer is 0 it is even, if it is 1 it is odd.
Example:
int test = 12
if (test % 2 == 0)
System.out.print("Even.");
else
System.out.print("Odd.");
You can incorporate this in the addition and subtraction operators.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I can't figure out why the following program doesn't work. Please help me where did I make a mistake. Thank you.
import java.util.Scanner;
public class LargestNumber {
public static void main(String[] args) {
int[] numbers = new int[100];
int largestNumber = 0;
System.out.println("Enter numbers. When you want to finish, type 'finish'.");
Scanner sc = new Scanner(System.in);
do {
if (sc.hasNextInt()) {
for (int counter = 0; counter < 10; counter++)
numbers[counter] = sc.nextInt();
}
if (!sc.hasNextInt() && !sc.hasNext("finish")) {
System.out.println("It's neither number nor 'finish'.");
}
}
while (!sc.hasNext("finish"));
for (int x : numbers) {
if (x > largestNumber) {
largestNumber = x;
}
}
System.out.println("The largest number is: " + largestNumber);
}
}
This part:
do {
if (sc.hasNextInt()) {
for (int counter = 0; counter < 10; counter++)
numbers[counter] = sc.nextInt();
}
if (!sc.hasNextInt() && !sc.hasNext("finish")) {
System.out.println("It's neither number nor 'finish'.");
}
}
while (!sc.hasNext("finish"));
makes no sense. You:
test if the next thing in the input is an integer;
attempt to parse ten next tokens, assuming that they are all integers;
at the eleventh token you check whether it's another integer or "finish";
throw an exception if it's neither;
repeat everything if it's not "finish".
What you should actually do is something much, much simpler:
check next token:
if it's "finish", you're done;
if it's an integer, parse it;
otherwise throw error;
repeat this for up to 100 times;
you are done accepting input. Proceed to processing it.
I think that Scanner is unnessecarily complicated and doesn't work to much of the time. Here's how to do it the old fashioned way:
public class LargestNumber {
public static void main(String[] args) {
int largestNumber=0;
System.out.println("Enter numbers. When you want to finish, type 'finish'.");
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
String line;
while (!(line = r.readLine()).equals("finish")) {
int val = Integer.parseInt(line);
if (val > largestNumber)
largestNumber = val;
}
System.out.println("The largest number is: " + largestNumber);
}
}
For this, enter each number on a new line. I used a shorter algorithm here, which is to read one number, and if it is bigger than the maximum so far, the new number is the maximum so far
According to the doc:
Throws:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
So i thing you could do this instead:
int counter = 0;
while (counter < numbers.length) {
if (sc.hasNextInt()) {
numbers[counter++] = sc.nextInt();
} else {
if (sc.hasNext("finish")) {
sc.close();
break;
} else {
System.out.println("It's neither number nor 'finish'.");
sc.next();
}
}
}
for (int x : numbers) {
if (x > largestNumber) {
largestNumber = x;
}
}
System.out.println("The largest number is: " + largestNumber);
hope that helps