Why isn't my Java number input code working? - java

I have been trying to figure out why isn't my code working. If I don't do it through a method and put this code in the main method then it keeps repeating. I want to ask the user for a new number every time. And then see if the number is odd or even. If odd then increase the odd count add all the numbers that the user enters. The user should be asked to enter values until the number 0 is entered.
package Week1;
import java.util.Scanner;
public class Task12 {
public void numbers() {
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
System.out.println("Enter number");
int oddnumbers = 0;
do {
int count = 0;
count = count + i;
System.out.println("The total is:" + count);
if (i % 2 == 0) {
System.out.println("The number is Even");
} else if (i != 9) {
oddnumbers += i;
System.out.println("The number is odd");
System.out.println("the count of odd numbers is :" + oddnumbers);
} else
System.out.println("The number is odd");
System.out.println("the count of odd numbers is :" + oddnumbers);
} while (i != 0);
}
public static void main(String[] args) {
Task12 n = new Task12();
n.numbers();
}
}

You should probably have the reading of a number "i = sc.nextInt();" inside the loop, and the variable count outside, like this:
package Week1;
import java.util.Scanner;
public class Task12 {
public void numbers() {
Scanner sc = new Scanner(System.in);
int oddnumbers = 0;
int count = 0;
int i=0;
do {
System.out.println("Enter number");
i = sc.nextInt();
count = count + i;
System.out.println("The total is:" + count);
if (i % 2 == 0) {
System.out.println("The number is Even");
} else if (i != 9) {
oddnumbers += i;
System.out.println("The number is odd");
System.out.println("the count of odd numbers is :" + oddnumbers);
} else
System.out.println("The number is odd");
System.out.println("the count of odd numbers is :" + oddnumbers);
} while (i != 0);
}
public static void main(String[] args) {
Task12 n = new Task12();
n.numbers();
}
}

This code gives the answer to tour spec/question
Reason for not working: You should take input inside do while loop and then check for odd.
public int numbers() {
Scanner sc = new Scanner(System.in);
int num = 0;
int oddSum = 0;
do {
System.out.println("Enter number");
num = sc.nextInt();
if(num == 0) {
break;
} else if (num % 2 != 0) {
oddSum += num;
}
} while (num != 0);
sc.close();
return oddSum;
}
public static void main(String[] args) {
Test n = new Test();
System.out.println(n.numbers());
}

Related

java game with tries options

I'm making a Guessing Game using Java and I need to add an option to count the number of guesses, but if the player gives the same answer multiple times, It will be count that as 1 try.
I don’t know how to proceed. Any help will be appreciated :)
Here's my current script:
import java.util.Scanner;
public class GuessTheNumber {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
int count = 0;
int a = 1 + (int) (Math.random() *9);
int guess = 0;
System.out.printf("Guess the number from 1 - 10: ");
while (guess != a) {
guess = keyboard.nextInt();
count++;
if (guess > a) {
System.out.printf("Lower!: ");
} else if (guess < a) {
System.out.printf("Higher!: ");
}
}
System.out.println("Congratulations! You guessed the number with "
+ count + " tries.");
}
}
You need to track all user's answers using a list so that you can iterate to the list if a similar answer exists before incrementing.
here it's pal
public class GuessTheNumber {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
ArrayList<Integer> answers = new ArrayList<Integer>();
;
int count = 0;
int a = 1 + (int) (Math.random() * 9);
int guess = 0;
System.out.printf("Guess the number from 1 - 10: ");
while (guess != a) {
guess = keyboard.nextInt();
boolean isAnswered = false;
for (Integer answer : answers) {
if (guess == answer) {
isAnswered = true;
break;
}
}
if (!isAnswered) {
count++;
answers.add(guess);
}
if (guess > a) {
System.out.printf("Lower!: ");
} else if (guess < a) {
System.out.printf("Higher!: ");
}
}
System.out.println("Congratulations! You guessed the number with "
+ count + " tries.");
}
}

Program that checks if the number is prime or not finds 45 as a prime number

Same thing happens when I type in number: 15,21,27,33 etc, basically every odd number divisible by 3.
Here's the code:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter Number");
int n = scanner.nextInt();
for (int i = 2; i < n/2; ++i) {
if (n % i == 0) {
System.out.println("Not Prime");
break;
}
else{
System.out.println("Prime");
break;
}
}
}
}

How do you reset a counter in Java for multiple inputs?

Hello I am trying to reset a counter in java, as I need to print out both the number of factors of a number and the sum of the factors. When I enter multiple integer values, these counters keep adding up. Is there a way in java to reset the counters after each new integer entered? Here is my code so far.
import java.util.Scanner;
public class FindFactors {
public static void main (String args[]) {
Scanner in = new Scanner(System.in);
int num, factorcounter = 0;
int sumfactors = 0;
System.out.print("Enter a positive integer.");
while(in.hasNextInt()) {
num = in.nextInt();
if(num > 0) {
for(int i = 1; i <= num; i++) {
if(num % i == 0) {
factorcounter++;
System.out.println(i + " is a factor of " + num);
sumfactors = sumfactors + i;
}
}
System.out.println("The number of factors: " + factorcounter);
if (sumfactors / 2 == num) {
System.out.println(num + " is a perfect number!");
}
}
else {
System.out.println("Invalid Input");
}
}
}
}
You have to assign zero to your variables.
Scanner in = new Scanner(System.in);
int num,factorcounter = 0;
int sumfactors = 0;
System.out.print("Enter a positive integer.");
while(in.hasNextInt())
{
num = in.nextInt();
factorcounter = 0;
sumfactors = 0;
if(num > 0)
{
for(int i = 1; i <= num; i++)
{
if(num % i == 0)
{
factorcounter++;
System.out.println(i + " is a factor of " + num);
sumfactors = sumfactors + i;
}
}
System.out.println("The number of factors: " + factorcounter);
if (sumfactors/2 == num)
{
System.out.println(num + " is a perfect number!");
}
}
else
{
System.out.println("Invalid Input");
}
}

How can I count the number of odd, evens, and zeros in a multiple digit number in Java?

Basically I need to write a program that takes user input up to and including 2^31 -1 in the form of an integer and returns the amount of odd, even, and zero numbers in the int. For example,
Input: 100
Output: 1 Odd, 0 Even, 2 Zeros // 1(Odd)0(Zero)0(Zero)
or
Input: 2034
Output: 1 Odd, 2 Even, 1 Zero // 2(Even)0(Zero)3(Odd)4(Even)
I'm pretty sure I'm over thinking it but I can't slow my brain down. Can anyone help?
This is the third iteration of the code, the first two were attempted with for loops.
import java.util.Scanner;
public class oddEvenZero
{
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
int value;
int evenCount = 0, oddCount = 0, zeroCount = 0;
System.out.print("Enter an integer: ");
value = scan.nextInt();
while (value > 0) {
value = value % 10;
if (value==0)
{
zeroCount++;
}
else if (value%2==0)
{
evenCount++;
}
else
{
oddCount++;
}
value = value / 10;
}
System.out.println();
System.out.printf("Even: %d Odd: %d Zero: %d", evenCount, oddCount, zeroCount);
}
}
Sorry, the code formatted weirdly in the textbox.
value = value % 10;
Probably the end-all-be-all of your problems.
If value is 2034, then value % 10 returns 4... and then assigns that value to value, you go through your if else block, then do 4/10 get 0, and exit the while loop without addressing the other 3 digits.
I suggest something more like this:
while (value > 0) {
if ((value%10)==0) {
zeroCount++;
}
else if (value%2==0) { //As per comment below...
evenCount++;
}
else {
oddCount++;
}
value /= 10;
}
Or, int thisDigit = value % 10, then replace value in your current if else block with thisDigit.
value = value % 10;
This statement will override your original value with a reminder i.e value % 10.
If value = 2034 and value % 10 = 4, then value = 4 which isn't what you want.
Instead use a temporary variable
int lastDigit = value % 10;
Then your code becomes;
while (value > 0) {
int lastDigit = value % 10;
if (lastDigit==0)
{
zeroCount++;
}
else if (lastDigit%2==0)
{
evenCount++;
}
else
{
oddCount++;
}
value = value / 10;
}
import java.util.Scanner;
public class oddEvenZero
{
public int[] convertStringArraytoIntArray(String[] sarray) throws Exception {
if (sarray != null)
{
int k= sarray.length-1;
int intarray[] = new int[k];
for (int i = 1; i < sarray.length; i++) {
intarray[i-1] = Integer.parseInt(sarray[i]);
}
return intarray;
}
return null;
}
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
String value;
System.out.print("Enter an integer: ");
value = scan.next();
String words[] = value.split("");
oddEvenZero obj = new oddEvenZero();
try{
int intarray[]= obj.convertStringArraytoIntArray(words);
int even_number =0;
int odd_number =0;
int zero_number =0;
for (int h: intarray)
{
if(h==0)
{
zero_number++;
}
else if(h%2==0)
{
even_number++;
}
else{
odd_number++;
}
}
System.out.println("even numbers are"+ even_number);
System.out.println("odd numbers are"+odd_number);
System.out.println("Zero numbers are"+zero_number);
}
catch(Exception ex)
{
System.out.println("Please enter number");
}
}
}
If some of you are still unable to figure this code out, I found this while searching around for a bit, and works just fine:
import java.util.*;
public class Java_1
{
public static void main (String[] args)
{
String string;
int zero = 0, odd = 0, even = 0, length, left = 0;
Scanner scan = new Scanner(System.in);
System.out.print ("Enter any positive number: ");
string = scan.next();
length = string.length();
while (left < length)
{
string.charAt(left);
if (string.charAt(left) == 0)
zero++;
else if (string.charAt(left) % 2 == 0)
even++;
else
odd++;
left++;
}
System.out.println ("There are: "+ zero + " zeros.");
System.out.println ("There are: "+ even + " even numbers.");
System.out.println ("There are: "+ odd + " odd numbers.");
}
}

How to add within a while loop in java?

Thank you for looking at my code.
I am learning java and have run into an issue that is driving me crazy.
/*
* The loop reads positive integers from standard input and that
* terminates when it reads an integer that is not positive. After the loop
* terminates, it prints out, separated by a space and on a single line, the
* sum of all the even integers read and the sum of all the odd integers
*/
The thing is that the variables are not adding! I know my syntax is good. I think there something about the java language that I don't understand with how loop works and adds.
import java.util.Scanner;
class Testing2 {
public static void main(String[] args) {
int sumP = 0;
int sumO = 0;
Scanner stdin = new Scanner(System.in);
System.out.println("Enter a positive or negative integer: ");
while ((stdin.nextInt()) >= 0) {
if (stdin.nextInt() % 2 == 0)
sumP += stdin.nextInt();
else
sumO += stdin.nextInt();
}
System.out.println(sumP + " " + sumO);
stdin.close();
}
};
Every time you call stdin.nextInt() it is looking for another integer. To avoid this, at the top set a variable equal to the input:
int myInt = stdin.nextInt();
if (myInt >= 0) {
if (myInt % 2 == 0)
sumP += myInt;
else
sumO += myInt;
}
System.out.println(sumP + " " + sumO);
stdin.close();
}
}
You do not put the semicolon after the last curly brace as well. If you are expecting multiple numbers to be input you can continually check for the next it with,
while(stdin.hasNext()){
int myInt = stdin.nextInt();
}
I think this solves the problem,
Scanner stdin = new Scanner(System.in);
while(1)
{
int num = stdin.nextInt();
if(num<0)
{
stdin.close();
break;
}
else
{
if(num%2==0)
{
//Initialize sumP and sumO to 0
sumP=sumP+num;
}
else
{
sumO=sumO+num;
}
}
//You can now output sumP and sum) outside the loop safely.
}
The problem is that you are using nextInt() every time.
Use like this-
import java.util.Scanner;
class Testing2 {
public static void main(String[] args) {
int sumP = 0;
int sumO = 0;
Scanner stdin = new Scanner(System.in);
System.out.println("Enter a positive or negative integer: ");
int temp;
while ((temp=stdin.nextInt())>0) {
if (temp % 2 == 0)
sumP += temp;
else
sumO += temp;
}
System.out.println(sumP + " " + sumO);
stdin.close();
}
}
while ((stdin.nextInt()) >= 0) {
if (stdin.nextInt() % 2 == 0)
sumP += stdin.nextInt();
else
sumO += stdin.nextInt();
}
Your problem is that you're reading in 3 numbers each time you loop. Store the result of your read and then decided what to do with it, don't discard it and read 2 more numbers.
int nextInt;
while ((nextInt = stdin.nextInt()) >= 0) {
// Do things with nextInt
}
I think you want to need coding like this
import java.util.Scanner;
class TestScaner {
public static void main(String[] args) {
int sumP = 0;
int sumO = 0;
Scanner stdin = null;
while (true) {
stdin = new Scanner(System.in);
System.out.println("Enter a positive or negative integer: ");
int num = stdin.nextInt();
if (num % 2 == 0)
sumP += num;
else
sumO += num;
System.out.println("==" + sumP + " " + sumO);
}
}
};
Please try these code
import java.util.Scanner;
class Testing2 {
public static void main(String[] args) {
int sumP = 0;
int sumO = 0;
int scn = 0;
Scanner stdin = new Scanner(System.in);
System.out.println("Enter a positive or negative integer: ");
scn = stdin.nextInt();
while (scn >= 0) {
System.out.println("stdin next " + scn);
if (scn % 2 == 0){
sumP += scn;
}else{
sumO += scn;
}
scn--;
}
System.out.println(sumP + " " + sumO);
}
};
your stdin.nextInt() does not decrease it only return a value of your stdin that is why it doesn't loop properly.
u also should put scanner inside while:
do {
Scanner stdin = new Scanner(System.in);
if (stdin.nextInt() % 2 == 0)
sumP += stdin.nextInt();
else
sumO += stdin.nextInt();
}while ((stdin.nextInt()) >= 0)

Categories

Resources