When I run this nothing prints, I am trying to print a message saying odd or even depending on what the user types.
import java.util.Scanner;
public class Questions {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Your number");
int number = input.nextInt();
for (int i = 0; i > 0; i = +2) {
if (number == i) {
System.out.println("even");
} else {
System.out.println("odd");
}
}
}
}
Your loop is never entered, because you initialize i with 0 and your first test is i > 0 (and you don't want a unary 2, = +2). I would also use formatted IO. Putting that together, I think you wanted something like
int number = input.nextInt();
for (int i = 0; i < number; i++) {
if ((i % 2) == 0) {
System.out.printf("%d even%n", i);
} else {
System.out.printf("%d odd%n", i);
}
}
If you're trying to avoid modulo (and use addition by 2) you could optimize with something like
int number = input.nextInt();
for (int i = 0; i < number; i += 2) {
System.out.printf("%d even%n", i);
System.out.printf("%d odd%n", i + 1);
}
Try this
import java.util.Scanner;
public class Questions {
public static void main (String[]args) {
Scanner input= new Scanner(System.in);
System.out.println("Your number");
int number = input.nextInt();
if(number % 2 == 0)
System.out.println("even");
}else {
System.out.println("odd");
}
}
may be you want to try this way...
if ((number % 2) ==0) {
System.out.println("even");
} else {
System.out.println("odd");
}
As you initialize i and the condition seems to be i>0 so it will always be false so for loop never executed
As #MadProgrammer stated in comments your loop never executed.
because i = 0, the loop is never executed ;)
Related
I need to write for each number the sequence output even if the number is even, otherwise, odd. If the number is equal to 0, the program must stop reading and processing numbers.
Input
1
2
3
0
Output
odd
even
odd
My code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int num;
for (; ; ) {
Scanner reader = new Scanner(System.in);
num = reader.nextInt();
if (num % 2 == 0) {
System.out.println("even");
}
else if(num == 0){
break;
}
else{
System.out.println("odd");
}
}
}
}
The issue with your posted code is addressed in the comment (checking num % 2 == 0 first), but in this case we can improve upon your solution. First, it's "idiomatic" in Java1 to use a while loop with a test after assignment. Second, it's possible to use a ?: conditional operator (a ternary) and remove the remaining if / else. Like,
int num;
Scanner reader = new Scanner(System.in);
while ((num = reader.nextInt()) != 0) {
System.out.println(num % 2 == 0 ? "even" : "odd");
}
1I don't know who defines idioms, but I didn't invent it. And I've seen this construct in JDK source.
int num;
Scanner reader = new Scanner(System.in);
for ( ; ; ) {
num = reader.nextInt();
if (num == 0) {
break;
} else if (num % 2== 0) {
System.out.println("even");
} else {
System.out.println("odd");
}
}
Your problem is the sequence of your if/else conditions. If the first input is 0, 0 % 2 returns true - so it will never break.
Also, you do not need a new Scanner every time. You can take it out of the loop and reuse it.
You need to check if the value is zero before checking if the value is even.
For example:
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int num;
while(true) {
num = reader.nextInt();
if(num == 0) break;
else if(num % 2 == 0) System.out.println("even");
else System.out.println("odd");
}
}
public static void main(String[] args) {
one();
System.out.println();
}
public static void one() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number:");
int i = sc.nextInt();
for (int j=0; j<i; j++) {
System.out.println(fibonacci(j));
}
}
public static int fibonacci(int num){
if (num == 1) {
return 0;
}
else if (num == 2 || num == 3){
return 1;
}
else {
return fibonacci(num-1) + fibonacci(num-2);
}
}
When I run this will get Exception in thread "main" java.lang.StackOverflowError but if I change one() to
public static void one() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number:");
int i = sc.nextInt();
System.out.println(fibonacci(j));
}
I wont get error, even I just enter 1, could I ask why?
You don't handle the case of num == 0, so when you call fibonacci(0) the recursion never ends, leading to StackOverflowError when the stack is full.
You can solve it by changing the range of your loop
for (int j=1; j<i; j++) {
System.out.println(fibonacci(j));
}
or by changing the stopping condition of your recursive method:
public static int fibonacci(int num) {
if (num <= 1) {
return 0;
}
else if (num == 2 || num == 3){
return 1;
}
else {
return fibonacci(num-1) + fibonacci(num-2);
}
}
That said, it would be much more efficient to store the intermediate results of fibonacci(i), and re-use them when calculating fibonacci(n) for n > i (instead of making unnecessary expansive recursive calls).
In the for-Statement you start with 0. This is the first Input to fibonacci-Funktion. Try:
public static void one() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number:");
int i = sc.nextInt();
for (int j=1; j<i; j++) {
System.out.println(fibonacci(j));
}
I think you missed to handle the zero. Just try the following loop,
for (int j=1; j<=i; j++) {
System.out.println(fibonacci(j));
}
I am doing a school project and I kinda got blocked.
I am looking forward building a javascript that asks the user of a number between 1 and 20 and then finds and lists all the multiples of that number inside range 0 and 100.
Here is what it looks like at the moment:
public static void main(String[] args) {
Scanner lector = new Scanner(System.in);
System.out.println("*** Program start ***\n");
System.out.println("Insert number [integer, between 1 and 20]: ");
boolean okay = false;
while (!okay) {
int n1 = lector.nextInt();
lector.nextLine();
if (n1<1 || n1>20) {
System.out.print("Invalid number!\nplease try again [between 1 and 20]: ");
} else {
okay = true;
System.out.println("Number accepted!");
}
int i = 0;
while (i <= 100) {
System.out.println(i);
if ((n1%100) == 0) {
System.out.println(n1);
}
i = i + 1;
}
System.out.println("\n*** End ***");
}
}
}
I am obviously bad at math cause I can't get the formula to work.
Thank you in advance!
public static void main(String[] args) {
Scanner lector = new Scanner(System.in);
System.out.println("*** Program start ***\n");
System.out.println("Insert number [integer, between 1 and 20]: ");
boolean okay = false;
while (!okay) {
int n1 = lector.nextInt();
lector.nextLine();
if (n1<1 || n1>20) {
System.out.print("Invalid number!\nplease try again [between 1 and 20]: ");
} else {
okay = true;
System.out.println("Number accepted!");
}
int i = 0;
while (i <= 100) {
System.out.println(i);
if ((n1%i) == 0) {
System.out.println(i);
}
i = i + 1;
}
System.out.println("\n*** End ***");
}
}
}
All multiples that fall between 0 and 100? That's the kind of thing for-loops are made for. After performing your IO and reading the number n1, change that while loop to the following.
for (int i = n1; i >= 0 && i <= 100; i = i + n1) {
System.out.println(i);
}
In case you aren't familiar with for loops, this basically says, set i to the value of n1, and keep adding n1 to it, printing each value as you go. When it leaves the range of 0..100, it terminates. So for instance, if 8 is entered it goes 8, 16, 24, 32, ..., 80, 88, 96.
If you really want to use a while loop, then try:
int i = n1;
while(i >= 0 && i <= 100) {
System.out.println(i);
i = i + n1;
}
public static void main(String[] args) {
Scanner lector = new Scanner(System.in);
System.out.println("*** Program start ***\n");
System.out.println("Insert number [integer, between 1 and 20]: ");
boolean okay = false;
while (!okay) {
int n1 = lector.nextInt();
lector.nextLine();
if (n1<1 || n1>20) {
System.out.print("Invalid number!\nplease try again [between 1 and 20]: ");
} else {
okay = true;
System.out.println("Number accepted!");
}
int i = 0;
while (i <= 100) {
System.out.println(i);
if ((n1*i) <= 100) {
System.out.println(i);
}
i = i + 1;
}
System.out.println("\n*** End ***");
}
}
}
This should work. You were just finding if the number n1 was divisible by 100.
I want to display the prime number required by the user. For example, if the user wants 3rd prime, I will display 5. I have the following java code.
import java.util.Scanner;
public class Prime {
private static Scanner scanner;
public static void main(String args[]) {
//get input till which prime number to be printed
// System.out.println("Enter which prime number to be printed: ");
// scanner = new Scanner(System.in);
// int limit = scanner.nextInt();
int count = 0;
int number = 2;
//System.out.println("Printing prime number from 1 to " + limit);
while(count<=3)
{
if(isPrime(number)){
count++;
// System.out.println(count);
}
number++;
}
if(count == 3)
System.out.println("10001 prime is "+number);
}
public static boolean isPrime(int number){
for(int i=2; i<number; i++){
if(number%i == 0){
return false;
}
}
return true;
}
}
When i run it, I am not able to gett any output. Where am i going wrong?
PS: For time being, I am running the loop only until 3.
You have while(count <= 3) so when you exit the loop, count == 4.
Therefore, your if(count == 3) is never entered and nothing is printed.
Anyways the better solution would be
public void calcPrime(int inp) {
ArrayList<Integer> arr = new ArrayList<Integer>();
arr.add(2);
arr.add(3);
int counter = 4;
while(arr.size() < inp) {
if(counter % 2 != 0 && counter%3 != 0) {
int temp = 4;
while(temp*temp <= counter) {
if(counter % temp == 0)
break;
temp ++;
}
if(temp*temp > counter) {
arr.add(counter);
}
}
counter++;
}
System.out.println("finish" +arr.get(inp-1));
}
}
Here is corrected code that works.
public class Main {
public static void main(String args[]) {
//Returns fourth prime number
System.out.println(getPrimeNumber(4));
}
public static int getPrimeNumber(int order) {
int currentOrder = 1;
int currentNumber = 1;
while (currentOrder < order) {
currentNumber++;
if (isPrime(currentNumber)) currentOrder++;
}
return currentNumber;
}
public static boolean isPrime(int number) {
for (int i = 2; i < number; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
There was no need to start your counter at 0 and it mathematically wrong to start with number 2 ! Just begin with order and currentNumber initialized at 1 and if first prime number is what your user is looking for, no loop will be required !
Also, your loop condition after correct variable initialization was corrected from "<=" to "<".
That's all !
In Java, I am having trouble running multiple loops using a single sequence of user-inputted integers. Individually, they run fine individually but together it prints out incorrect numbers.
I'm at a loss as to what is causing this problem.
Here is my code.
import java.util.Scanner;
public class SequenceTester
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a sequence of integers. " +
"Enter a non-integer to terminate");
int sequence = in.nextInt();
//Print One
int min = sequence;
while(in.hasNextInt())
{
int input = in.nextInt();
if(input < smallest)
{
smallest = input;
}
}
System.out.println(smallest);
//Print Two
int max = sequence;
while(in.hasNextInt())
{
int input = in.nextInt();
if(input > max)
{
max = input;
}
}
System.out.println(max);
//Print Three
int even = 0;
int odd = 0;
while(in.hasNextInt())
{
int input = in.nextInt();
if((input %2) == 0)
{
even++;
}
else
{
odd++;
}
}
System.out.println( even);
System.out.println(odd);
//Print Four
double total = 0;
int count = 0;
while (in.hasNextInt())
{
Int input = in.nextInt();
total = total + input;
count++;
}
double average = 0;
if (count > 0)
{
average = total / count;
}
System.out.println(average);
}
}
Your code is very fragmented, but it looks like you can achieve what you want with one loop since the loop condition is the same in all of them. This, of course, is only based on the vague description you gave us.
while(in.hasNextInt()) {
int input = in.nextInt();
if(condition1) {
//do stuff
} else if (condition2) {
//do other stuff
} else if (conditionN) {
//do other other stuff
} else {
//last of the stuff to do
}
}