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)
Related
My factorial method is working correctly although I would like to change the output from just outputting the number and the factorial result. For example I would like if the user enters 6 for the output to say 6 * 5 * 4 * 3 * 2 * 1 = 720, instead of factorial of 6 is: 720.
int count, number;//declared count as loop and number as user input
int fact = 1;//declared as 1
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Please enter a number above 0:");
number = reader.nextInt(); // Scans the next token of the input as an int
System.out.println(number);//prints number the user input
if (number > 0) {
for (i = 1; i <= number; i++) {//loop
fact = fact * i;
}
System.out.println("Factorial of " + number + " is: " + fact);
}
else
{
System.out.println("Enter a number greater than 0");
}
}
create a string and store the numbers.
try something like this.
int count, number;//declared count as loop and number as user input
String s; //create a string
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Please enter a number above 0:");
number = reader.nextInt(); // Scans the next token of the input as an int
int fact = number;//store the number retrieved
System.out.println(number);//prints number the user input
if (number > 0) {
s=String.valueOf(number);
for (int i = 1; i < number; i++) {//loop
fact = fact * i;
s = s +" * "+String.valueOf(number-i);
}
System.out.println(s+ " = " + fact);
}
else
{
System.out.println("Enter a number greater than 0");
}
Check out this recursive approach: (check negative numbers yourself :D)
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
System.out.println(getFactorialString(num, " = " + getFactorial(num)));
}
public static String getFactorialString(int num, String result) {
if (num == 0) return "0 => 1";
if (num == 1) {
result = "" + num + "" + result;
} else {
result = getFactorialString(num - 1, result);
result = "" + num + " x " + result;
}
return result;
}
public static int getFactorial(int num) {
if (num == 0) return 1;
return num * getFactorial(num - 1);
}
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());
}
Values are entered until a 0 is entered. Then the program ends, but before that happens the sum of all values are given if they were Integral numbers.
This is what I have tried so far but I'm stuck.
public class Aufgabe2 {
public static void main(String[] args) {
/* TODO: add code here */
int n;
int sum = 0;
boolean exit = true;
Scanner input = new Scanner(System.in);
while (true) {
n = input.nextInt();
if (n == 0) {
exit = true;
} else {
sum += n;
System.out.println(sum);
}
}
}
}
There is some good doco on Scanner on the oracle website: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Scanner will throw an error in the event that the token you are expecting is not there. I would recommend you check for an integer input.hasNextInt() before you attempt to parse it.
Something like this:
int sum = 0;
boolean exit = true;
Scanner input = new Scanner(System.in);
while (input.hasNextInt()) {
int n = input.nextInt();
if (n == 0) {
break;
} else {
sum += n;
}
}
// Print outside of the loop
System.out.println(sum);
Result of the program
Input:
1
2
3
0
Output:
6
Try;
int n;
int sum = 0;
boolean exit = true;
Scanner input = new Scanner(System.in);
while (exit) {
n = input.nextInt();
if (n == 0) {
exit = false;
}
else {
sum += n;
System.out.println(sum);
}
}
You have a while(true) which is a continuous loop.
Working code:
import java.util.*;
public class Aufgabe2 {
public static void main(String[] args) {
/* TODO: add code here */
int n;
int sum = 0;
boolean exit = false;
Scanner input = new Scanner(System.in);
while (!exit) {
System.out.println("Enter a number:");
n = input.nextInt();
if (n == 0) {
exit = true;
} else {
sum += n;
System.out.println(sum);
}
}
}
}
Output:
Enter a number:
1
1
Enter a number:
3
4
Enter a number:
6
10
Enter a number:
0
Edit:
You have to change while (true) loop to use boolean variable exit. I have modified the code accordingly and corrected the while loop condition.
I have created a program using Java that generates emirps by user input, but I need help on stopping the user when entering zero or a negative integer. I have tried many things but when I run the program with zero or a negative number it will go crazy and give me infinite amount of numbers. I would appreciate it if someone could help me on this.
Here is what I got so far...
import java.util.Scanner;
public class GenerateEmirps {
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
System.out.print("Enter number of desired emirps: ");
int emrips = scanner.nextInt();
int count = 1;
for( int i = 2; ; i++){
if ((isPrime(i)) && (isPrime(reverseIt(i))) && (!isPalindrome(i))) {
System.out.print(i + " ");
if (count % 10 == 0) {
System.out.println();
}
if (count == emrips){
break;
}
count++;
}
}
}
public static boolean isPrime(int num){
for (int i = 2; i <=num / 2; i++){
if (num % i == 0) {
return false;
}
}
return true;
}
public static int reverseIt(int num){
int result = 0;
while (num != 0) {
int lastDigit = num % 10;
result = result * 10 + lastDigit;
num /= 10;
}
return result;
}
public static boolean isPalindrome(int num){
return num == reverseIt(num);
}
}
Solution:
You just need to test the input before you process it.
int emrips = scanner.nextInt();
if (emrips <= 0) { System.exit(0); }
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.");
}
}