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.
Related
I am trying to prompt the user to enter 5 integers but it won't loop more than once. I don't know why this is happening and couldn't resolve the error by myself
Code:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s= new Scanner(System.in);
int counter= 0;
Boolean inputOK;
int iInput;
int data[]= new int[5];
// while (counter<5);
do {
System.out.println(" Please enter an integer");
while (!s.hasNextInt()) {
System.out.println("Invalid input");
System.out.println("Please Enter an integer value");
s.next();}
iInput=s.nextInt();
if (iInput < -10 || iInput > 10) {
System.out.println("Not a valid integer. Please enter a integer between -10 and 10");
inputOK = false;
} else {
inputOK = true;
}
System.out.println("before while loop"+ inputOK);
} while (!inputOK);
counter++;
System.out.println("counter value is"+ counter);
}
}
If you follow your code, you can see that when inputOK is true, there is no loop to get back to. It looks like you had some counter in mind, but you ended up not using it. The following code does what I think you intended with your code:
Scanner sc = new Scanner(System.in);
int[] data = new int[5];
for(int i = 0; i < data.length; i++) {
System.out.println("Please enter an integer.");
// Skip over non-integers.
while(!sc.hasNextInt()) {
System.out.println("Invalid input: " + sc.next());
}
// Read and store the integer if it is valid.
int nextInt = sc.nextInt();
if(nextInt < -10 || nextInt > 10) {
// Make the for loop repeat this iteration.
System.out.println("Not a valid integer. Please enter an integer between -10 and 10.");
i--;
continue;
}
data[i] = nextInt;
}
for(int i = 0; i < data.length; i++) {
System.out.println("data[" + i + "] = " + data[i]);
}
Please try to base examples or explanations off of my code as I am a beginner there are many concepts that I do not understand.
import java.util.*;
public class Main{
public static void main(String[]args){
while(true) {
int i;
int x;
System.out.println("Enter a number.");
Scanner input = new Scanner(System.in);
int z = input.nextInt();
x=z/2;
}
for(int i=2; i <= int x ; i++)
if(z%i==0||z==0||z==1){
System.out.println("Not prime number");
}
else{
System.out.println("Prime Number");
}
}
Add isPrime() function that checks if the number is prime or not and print in the while-loop
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("Enter a number.");
int num = input.nextInt();
if (isPrime(num)) {
System.out.println("Prime Number");
} else {
System.out.println("Not prime Number");
}
}
}
private static boolean isPrime(int num) {
if (num == 0 || num == 1)
return false;
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number = 1;
int[] arrayNumber = new int[10];
do {
System.out.println("Please enter numbers (0 to stop) : ");
for (int i = 0; i < arrayNumber.length; i++) {
arrayNumber[i] = scanner.nextInt();
if (arrayNumber[i] == 0) {
number = 0;
}
}
} while (number != 0);
I am trying to have the user enter numbers (up to 10) and is stopped once the user enters 0. But, when 0 is entered it does not stop.
It is simply because you have an inner for loop, you're setting the number to 0 but the for loop still hasn't finished completing. Here would be the fix
This will finish executing after the user enters 10 numbers or enters 0, whichever comes first
Scanner scanner = new Scanner(System.in);
int[] arrayNumber = new int[10];
int maxNums = 0;
while (maxNums < 10) {
arrayNumber[maxNums] = scanner.nextInt();
if (arrayNumber[maxNums] == 0) break;
maxNums++;
}
This is much shorter and neater, more readable
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number = 1;
int[] arrayNumber = new int[10];
do {
System.out.println("Please enter numbers (0 to stop) : ");
for (int i = 0; i < arrayNumber.length; i++) {
arrayNumber[i] = scanner.nextInt();
if (arrayNumber[i] == 0) {
number = 0;
break;
}
} while (number != 0);
The point is that your code would work properly only if you enter 0 at the last iteration at for loop. You can explicitly break your loop to let the while loop process your zero value and stop the loop.
do {
System.out.println("Please enter numbers (0 to stop) : ");
for (int i = 0; i < arrayNumber.length; i++) {
arrayNumber[i] = scanner.nextInt();
if (arrayNumber[i] == 0) {
number = 0;
break;
}
}
} while (number != 0);
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.");
}
}