algorithm is not working with some inputs [closed] - java

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 1 year ago.
Improve this question
I'm new to programming, and I saw a problem in a website to practice. I was asked to create an algorithm that takes a positive integer, let's say n. If n is even the algorithm divides n by 2. If n is odd, it multiplies n by 3 and adds 1. This is repeated until it gets n = 1. For example, n=3 the the output would be 3 > 10 > 5 > 16 > 8 > 4 > 2 > 1
My code looks like this:
import java.util.*;
public class practice {
public static void solve(int n){
while(n > 1){
System.out.print(n + " ");
if(n % 2 == 0){
n=n/2;
}else{
n=(3*n)+1;
}
}
System.out.print(n);
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int input = keyboard.nextInt();
solve(input);
}
}
(Edit: Last output is suppose to be 1, but instead I'm getting random negative numbers with the next inputs):
138367
270271
665215
704511
I have no idea what I'm doing wrong...

I think int is going out or range or out of bytes after some calculation try the given code using long:
import java.util.*;
public class practice {
public static void solve(long n){
while(n > 1){
System.out.print(n + " ");
if(n % 2 == 0){
n=n/2;
}else{
n=(3*n)+1;
}
}
System.out.print(n);
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
long input = keyboard.nextLong();
solve(input);
}
}

Related

Multiples of 3 print hippity and on multiples of 4 print hop? [closed]

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
//Name of Program: HippityHop.java
//Entered by: No Name
//Date: 10/19/2020
import java.util.Scanner; // Needed for the Scanner class
public class HippityHop
{
public static void main(String[] args)
{
// get scanner to read input
Scanner keyboard = new Scanner(System.in);
for(int x=1; x <= 100; x++){
if(x % 3 && x % 4) {
System.out.println(x);
}else{
if(x % 3 == 0){
System.out.println("Hippity");
}
if(x % 4 == 0){
System.out.println("Hop");
}
}
}
}
}
I am trying to create a program that on multiples of 3 it prints "Hippity" and on multiples of 4 it prints "hop". I seem to be getting a bad operand error. What can I do to fix it?
The following expression:
if(x % 3 && x % 4) {
Isn't a proper one. What x%3 is doing is calculating the modulus. You never compared it to anything, so it's throwing a bad operand error. That's like saying in real life:
if x modulus 3 then do this
Or, just for the sake of the argument (and to make it easier to understand), it's like saying:
if x subtract 3 then do this
Instead, it should be if(x%3!=0 && x%4!=0), like so:
import java.util.Scanner; // Needed for the Scanner class
public class HippityHop
{
public static void main(String[] args)
{
// get scanner to read input
Scanner keyboard = new Scanner(System.in);
for(int x=1; x <= 100; x++){
if(x % 3 !=0 && x % 4 !=0) {
System.out.println(x);
}else{
if(x % 3 == 0){
System.out.println("Hippity");
}
if(x % 4 == 0){
System.out.println("Hop");
}
}
}
} }

InputMismatchException when reading float via Scanner.nextFloat() [closed]

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 3 years ago.
Improve this question
When I use the program with an integer value it works, but when I input a float (such as 47.3) it doesn't. Can you please help me in defining the problem?
the code:
package ex1;
import java.util.Scanner;
public class test {
static Scanner input = new Scanner(System.in);
public static void main (String[] args) {
float n;
System.out.println("enter a number:");
n = input.nextFloat();
if (n > 0 && n % 2 == 0) {
System.out.println("the number is positive and even");
}
else if (n > 0 && n % 2 != 0) {
System.out.println("the number is positive and odd");
}
else if (n < 0 && n % 2 == 0) {
System.out.println("the number is negative and even");
}
else if (n < 0 && n % 2 != 0) {
System.out.println("the number is negative and odd");
}
else if (n == 0) {
System.out.println("the number is zero");
}
}
}
the problem:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextFloat(Scanner.java:2496)
at ex1.test.main(test.java:14)
thanks
A comma is considered as a decimal separator in Java. So to use a Float input you should replace the '.' by ','

take input until input positive number [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Take two integers p & q ... Sum should be printed of p to next q numbers including p .. if q <= 0 , then it will take the value of q again ...
Input :::: 3 2
Output :::: 7 (p=3 & q = 2 ..... So from 3 to next 2 numbers are 3 & 4 as it will be included in the sum ... Now we will have to print the sum of 3+4 and that's 7 )
Input ::: 4 -1 1
Output :::. 4 ( as the next number is 4 )
That means we have to start counting from the taken integer ....
Solve it and drop the solution here ......
import java.util.Scanner;
public class Ahmed {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int p=sc.nextInt();
int q=sc.nextInt();
int sum=0;
if(q>=0){
for(int i=1; i<=q ;i++) {
sum=p+sum;
p++;
}
}
else{
q=sc.nextInt();
for(int i=1; i<=q ;i++) {
sum=p+sum;
p++;
}
}
System.out.println(sum);
}
}
if I take input 4 -1 -1 there is a error. Loop will continue until I take q input a positive number or 0;
Correct input 4 -1 -1 2 output 9.
Generally, when we have a loop and we dont know how many times it will repeat, we can use while.
Create a function like this:
private int readPositiveInt(Scanner sc){
int i = -1
while (i <= 0) {
i = sc.nextInt();
}
return i;
}
Then, you replace this line of code int q=sc.nextInt(); by this:
int q = readPositiveInt(sc);
Finally, once q will be positive for sure, you can remove these lines:
else{
q=sc.nextInt();
for(int i=1; i<=q ;i++) {
sum=p+sum;
p++;
}
}

Java 1 student totally lost. Recursion program

Hi very first Java class and it seems to be going a mile a minute. We learn the basics on a topic and we are asked to produce code for more advanced programs than what helped us get introduced to the topic.
Write a recursive program which takes an integer number as Input. The program takes each digit in the number and add them all together, repeating with the new sum until the result is a single digit.
Your Output should look like exactly this :
################### output example 1
Enter a number : 96374
I am calculating.....
Step 1 : 9 + 6 + 3 + 7 + 4 = 29
Step 2 : 2 + 9 = 11
Step 3 : 1 + 1 =2
Finally Single digit in 3 steps !!!!!
Your answer is 2.
I understand the math java uses to produce the output I want. I can do that much after learning the basics on recursion. But with just setting up the layout and format of the code I am lost. I get errors that make sense but have trouble correcting with my inexperience.
package numout;
import java.util.Scanner;
public class NumOut {
public static void main(String[] args) {
System.out.print("Enter number: ");
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
System.out.println(n);
}
public int sumDigit(int n){
int sum = n % 9;
if(sum == 0){
if(n > 0)
return 9;
}
return sum;
}
}
The output understandably duplicates the code given by the input from the user.
I had trouble calling the second class when I tried to split it up into two. I also know I am not soprln n, or the sum. So I try to make it into one and I can visibly see the problem but am unaware how to find the solution.
Think of recursion as solving a problem by breaking it into similar problems which are smaller. You also need to have a case where the problem is so small that the solution is obvious, or at least easily computed. For example, with your exercise to sum the digits of a number, you need to add the ones digit to the sum of all the other digits. Notice that sum of all the other digits describes a smaller version of the same problem. In this case, the smallest problem will be one with only a single digit.
What this all means, is that you need to write a method sumDigits(int num) that takes the ones digit of num and adds it to the sum of the other digits by recursively calling sumDigits() with a smaller number.
This is how you need to do : basically you are not using any recursion in your code. Recursion is basically function calling itself. Don't be daunted by the language, you will going to enjoy problem solving once you start doing it regularly.
public static void main(String []args){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
printSingleDightSum(n);
}
public static void printSingleDightSum(int N) {
int sum = 0;
int num = N;
while(num !=0 ){
int a = num%10;
sum + = a;
num = num/10;
}
if(sum < 10) {
System.out.println('single digit sum is '+sum);
return;
} else {
printSingleDightSum(sum);
}
}
Here is the code, I will add comments and an explanation later but for now here is the code:
package numout;
import java.util.Scanner;
public class NumOut {
public static void main(String[] args) {
System.out.println("################### output example 1");
System.out.print("Enter number: ");
final int n = new Scanner(System.in).nextInt();
System.out.print("\nI am Calculating.....");
sumSums(n, 1);
}
public static int sumSums(int n, int step) {
System.out.print("\n\nStep " + step + " : ");
final int num = sumDigit(n);
System.out.print("= " + num);
if(num > 9) {
sumSums(num, step+1);
}
return num;
}
public static int sumDigit(int n) {
int modulo = n % 10;
if(n == 0) return 0;
final int num = sumDigit(n / 10);
if(n / 10 != 0)
System.out.print("+ " + modulo + " ");
else
System.out.print(modulo + " ");
return modulo + num;
}
}

Program where user enters 2 inputs and a limit. It finds the sum of the multiples. please check [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
The user must enter x, y, and the limit. The program must find the multiples of these numbers that are below the limit that the user set themselves. The program adds up all the multiples and prints just that number at the end, and not all the multiples. For some reason it just isn't working for me and I can't figure it out.
import java.util.Scanner;
public class SumMultiples.java {
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter x value: ");
int x = scanner.nextInt();
System.out.print("Enter y value: ");
int y = scanner.nextInt();
System.out.print("Enter limit value: ");
int limit = scanner.nextInt()
int sum = 0;
for (int i = 0; i < limit; i++) {
if (((i % x) == 0 || ((i % y) == 0))) {
sum += i;
}
}
}
System.out.println(sum);
}
From copying your code into Eclipse:
Firstly you are missing a ; when you are getting the input for limit.
Secondly your System.out.println(sum); is outside of your main method, it should be at the end of the method i.e. after your for loop.
Thirdly, you have named your class SumMultiples.java. This is not a valid name, rename it to SumMultiples.
You should be getting compile errors and your IDE should help you work this out. If you aren't using an IDE, please do so as it will help you debug these issues and help you get familiar with Java.

Categories