How do i make multiple conditions in java? [closed] - java

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 8 years ago.
Improve this question
Write a program that does the following:
The program uses the Scanner object to ask the user for input of a whole number (integer).
If the user enters a whole number greater than or equal to 10 but less than 20, the program calculates the value of 10 raised to the power of the number entered and outputs that value, otherwise if the user enters a number greater or equal to zero but less than 10 the program calculates the product of 100 times the number entered and outputs that result. If the user enters the number -1 the program exits without providing an output. All other numbers entered are indicated as invalid entry numbers via an output statement stating so.
Input is received from user via the scanner object (from the keyboard) only once (no loop is needed in this program). Make sure that you output a statement first indicating to the user to enter whole numbers only.
Compile the program and test it for all conditions
Here is my code:
import java.util.Scanner;
public class Conditions
{
public static void main(String[] args)
{
Scanner scan=new Scanner(System.in);
System.out.println("Please enter a whole number");
int num1=scan.nextInt();
int num2=scan.nextInt();
int num3=scan.nextInt();
int num4=scan.nextInt();
if((num1>=10)||(num1<20))||(num1>=0)||(num1<10)||(num1==-1)||(num1>20);
System.out.println(Math.pow(10,num1));
System.out.println(100*num1);
System.out.println("Your entry is invalid");
System.exit(0);
}
}
What am I doing wrong. Thanks for the help in advance!

Do you mean you are asking how to do if statements? That would be the best way to handle these conditions. In your project description, you say if the user enters a number in the range 10 <= x < 20, then do an if statement doing exactly that.
if(num1 >= 10 && num1 < 20) {
//do your 10^num1 stuff
}
else if(num1 >= 0 && num1 < 10 ) {
//do the num * 100 stuff
}
else if(num1 > 20){
//number is > 20. Handle this however you have to.
}
else {
//num is in the negatives. Exit
}

Related

I was solving SPOJ problem 2 of PRIME GENERATOR. I am getting wrong answer as output by SPOJ compiler. Can someone help me? [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 2 years ago.
Improve this question
PROBLEM DESCRIPTION
Peter wants to generate some prime numbers for his cryptosystem. Help him! Your task is to generate all prime numbers between two given numbers!
Input
The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space.
Output
For every test case print all prime numbers p such that m <= p <= n, one number per line, test cases separated by an empty line.
Example
Input:
2
1 10
3 5
Output:
2
3
5
7
//----------BLANK SPACE BETWEEN TEST CASES-------------
3
5
import java.util.*;
import java.lang.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for(int i=0;i<t;i++)
{
boolean prime = true;
long m = in.nextLong();
long n = in.nextLong();
if(m<2)
{
System.out.println("2");
m=3;
}
for(int j=m;j<=n;j+=2)
{
int z = (int)Math.floor(Math.sqrt(j));
for(int k=2;k<=z;k++)
{
if(j%k==0)
{
prime=false;
break;
}
}
if(prime)
System.out.println(j);
}
System.out.println();
}
}
}
Your loops are using int datatype. It is lossy because you are comparing long with int. It will work for small numbers but constraints are too big so try using long.
Edit
I thought its because overflow without running it.
Your code has lots of problems
It will not work when m is even
you are not setting prime back to true in loop
Check these suggestions and comment is it working?
Solution
use long datatype in loop (that is not necessary)
set prime = true in inner loop
instead of incrementing by 2 i.e. j+=2, increment by 1 j+=1.

Homework problem on Java: I'm trying to run my program, it shows no error however when I try to run it it doesn't work? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
My homework is to create a program that tells how many calories you consumed depending on the numbers of cookies you ate. But when I run the program, it doesn't show anything and I need it to work for my homework.
Here's the code for more context:
package cookie.calories;
import java.util.Scanner;
public class CookieCalories {
public static void main(String[] args) {
Scanner ob = new Scanner(System.in);
int TotalNumberOfCookiesPerBag = 40;
int CaloriesPerServing = 300;
int ServingsPerBag = 10;
//The next equation represent the number of cookies per servings
int NumberOfCookiesPerServings = TotalNumberOfCookiesPerBag/ServingsPerBag;
//number of calories per cookies
int CaloriesPerCookies =CaloriesPerServing/NumberOfCookiesPerServings;
Scanner ob2 = new Scanner(System.in);
System.out.println("This programm can determined how many calories you ate depending on the number of cookie you ate.");
//Below this sentence, the amount of calories will be determined
System.out.println("Enter the number of cookies you ate");
int Cookies = ob.nextInt(4);
int TotalCaloriesConsumed = CaloriesPerCookies*Cookies;
System.out.println(TotalCaloriesConsumed + "for the amount of cookies you ate");
}
}
The program shows me that I didn't made any error in the way I wrote my program but when I play it, it doesn't show anything in the output. Why?
When I run your program I get this output
This programm can determined how many calories you ate depending on the number of
cookie you ate.
Enter the number of cookies you ate
when I enter (for example) 4 and press enter I get this error
Exception in thread "main" java.util.InputMismatchException: For input string: "4"
under radix 4
at java.base/java.util.Scanner.nextInt(Scanner.java:2264)
at testasdf.Testasdf.main(Testasdf.java:38)
Not really sure why you have "ob.nextInt(4);" instead of "ob.nextInt();" should change your code to be nextInt();
So I am unsure of why nothing is showing up for you, are you sure you have a output screen set up?
What IDE are you using?
Remove the '4' from the nextInt method params.
int Cookies = ob.nextInt();
Also you don't need another Scanner object, you can use the same one to get input from the user multiple times, so you can remove this from your code.
Scanner ob2 = new Scanner(System.in);

Counter Loop - Java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
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.
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.
Improve this question
Edit: I have found a way to work with CompareTo to help with this problem, but for some reason I cannot get the count down to work.
It's a negative number that needs to get more negative to meet the requirements, but I am missing something here. When I execute the down section it closes the program. So to me this means that I have something messed up and the program isnt seeing the problem and closing.
We are supposed to:
Ask the user for an integer then ask the user if he/she wants to count
up or down. Display a table of numbers where the first column contains
the counter, the second column contains the counter plus 10, and the
third column contains the counter plus 100. Make it so each number
takes up 5 spaces total.
If counting up, the first column should contain numbers 1 through the
user input; If counting down, the first column should contain numbers
-1 through the the negative of the user input;
Do user input validation on the word "up" and "down". Allow for any
case.
import java.util.Scanner;
public class ps1 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
//Comparision string already declared
String up = "up";
String down = "down";
//initialize the counters sum
int sum = 0;
//ask the user for a number
System.out.println("Enter an ending value");
int num1 = keyboard.nextInt();
keyboard.nextLine();
System.out.println("Count up or down?");
String input = keyboard.nextLine();
while (input.equalsIgnoreCase(up) || input.equalsIgnoreCase(down)) {
System.out.println("Count up or down?");
input = keyboard.nextLine();
}
if (input.compareToIgnoreCase(up) == 0) {
if (num1 >= 0)
for (int c = 1; c <= num1; c++) {
sum = sum + c;
System.out.printf("%5d%5d%5d\n", c, c + 10, c + 100);
else
System.out.println("Up numbers must be positive");
if (input.compareToIgnoreCase(down) == 0) {
for (int c1 = -1; c1 <= num1; c1--) {
sum = sum + c1;
System.out.printf("%5d%5d%5d\n", c1, c1 + 10, c1 + 100);
}
}
}
}
}
I see you have figured out core logic. BTW, your code will not compile, there is a syntax error.
Your code would look like this:
print(a a+10 a+100)
I know that it's not valid syntax but you would be able to figure out the correct way to write the code.
To print data properly, you will need following:
https://dzone.com/articles/java-string-format-examples
I would recommend visualizing the output first. In your case, it would look like following: (_are spaces)
Enter an ending value: 2
Direction: Up
____1___11__101
____2___12__102
Also, think about error cases. What will happen in following:
Enter an ending value: -10
Direction: Up
Error: Improper data
You are allowing user to enter a positive num1 and count down using for (int counter1 = -1; counter1 >= num1; counter1--). This makes no sense as counter1 >= num1 resolves to -1 >= 1 which is never true. When direction is down the number must be negative and when direction is up the number must be positive.
You might need to loop until user provides a valid direction. Currently you go down for any input that is not up. A possible solution would be to:
String input;
do {
input = keyboard.nextLine();
} while (!input.equalsIgnoreCase("up") && !input.equalsIgnoreCase("down"));
Please use shorter variable names. counter1 is scoped just to the for loop block so call it i. It's easier to read.
Whichever editor you are using configure auto formatting :)

Recursions With Integers (Very Basic) [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 6 years ago.
Improve this question
I am currently taking a HS course on java, so I am a novice at java to say the least. Right now, for my own use, I am writing a program to take a 2 digit number, and then add up it and all the odd numbers before it till 1. I have the Scanner, calculating whether the number is odd or even, and the runner methods done already(the basic bit), but am a bit confused on the logic. I am trying to use a recursion, and do this code, but am a bit stuck. It would be helpful if you could point me in the right direction, without giving the whole code away. Thanks, - A Novice Programmer
public static void main(String[] args)
{
MathRecursion tester = new MathRecursion();
tester.Method1Runner();
}
public void Method1Runner()
{
GetIntM1();
OddOrEven();
System.out.println("\n\n");
}
public void GetIntM1()
{
Scanner kb = new Scanner(System.in);
System.out.print("\n\n\nEnter a 2 digit integer: ");
twoDig = kb.nextInt();
}
public void OddOrEven()
{
if (twoDig % 2 == 0)
{
//This is even method
Method1a(twoDig);
}
else
{
//This is odd method
Method1b(twoDig);
}
}
public int Method1a(int a)
{
//if (a = 1)
int result = 0;
while (a<=b)
{
result+=a;
a++;
}
System.out.println("The sum of all numbers is "+result);
}
You don't need recursion. The sum of the first n odd numbers is n*n.
The number of odd numbers before a number x is floor(x/2) or in Java (int) x/2 or if x is an int, just x/2.
So the expression in Java that gives you "a 2 digit number, and then add up it and all the odd numbers before it till 1" where the number is stored in int x is:
x + (x/2) * (x/2)
or simplified:
x + x*x/4

Adding 1 one on to an integer each time? [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 6 years ago.
Improve this question
public class LockPicker {
public static void main(String[] args) {
System.out.println ("Picking the lock...");
boolean lock = false;
while (lock==false)
{
int counter = 0;
int number = (int)(Math.random() * 99 + 1);
System.out.println(number);
if (number!=55){
lock = false;
++counter;
}else{
lock = true;
System.out.println("That took "+counter+" tries!");
}
}
}
}
Hello,
I have been set a task where I have to write a program that will generate random numbers between 10 and 99. The program
should continue to repeat until the number 55 is created. The program should output how
many attempts it made to get 55.
It works fine, and stops when it reaches 55. However, the counter always remains at 0. It never adds 1 onto the variable counter.
Move the int counter = 0; line before the while loop.
Everytime the loop runs, you are initializing the counter variable to 0, that is why it always remains 0.

Categories

Resources