I'm having trouble finishing this program. I understand what the program is suppose to do, but I'm having trouble finishing it. I have my code posted below.
For this program I am required to determine if a number is a prime number. A part from this, I'm required to ask the user to enter a range (ex. 1-10) and display which numbers are prime and which are not.
This is what I have so far...
import java.util.Scanner;
public class PrimeNumbers
{
public static void main(String[]args)
{
//Create Scanner Object
Scanner input = new Scanner(System.in);
//Initialize variable
double num1, range;
//Prompt the user to enter in a number
do
{
System.out.println("Please enter in a number:");
num1 = input.nextDouble();
//Decision making
if(num1 % 2 == 0 || num1 % 3 == 0 || num1 % 4 == 0 || num1 % 5 == 0 || num1 % 6 == 0 || num1 % 7 ==0 || num1 % 8 ==0 || num1 % 9 == 0)
{
//Display message
System.out.println(num1 + " is not a prime number.");
System.out.println("Please enter a range: ");
range = input.nextInt();
if ()
}
else
//Display output
System.out.println(num1 + " is prime.");
}
while(num1 == -1);
{
System.out.println("This program has now ended.");
}
}
}
http://beginnersbook.com/2014/01/java-program-to-display-prime-numbers/
import java.util.Scanner;
class PrimeNumbers2
{
public static void main (String[] args)
{
Scanner scanner = new Scanner(System.in);
int i =0;
int num =0;
//Empty String
String primeNumbers = "";
System.out.println("Enter the value of n:");
int n = scanner.nextInt();
for (i = 1; i <= n; i++)
{
int counter=0;
for(num =i; num>=1; num--)
{
if(i%num==0)
{
counter = counter + 1;
}
}
if (counter ==2)
{
//Appended the Prime number to the String
primeNumbers = primeNumbers + i + " ";
}
}
System.out.println("Prime numbers from 1 to n are :");
System.out.println(primeNumbers);
}
}
Related
I'm fairly new to Java and the problem I am having is that this code compiles, but does not run after the hexadecimal conversion; it instead just ends after the method hexCharToDecimal. I can't reuse method main and I'm not sure how to call the method intreverse and actually have it run. Is there a way to get back into main or do I have to call intreverse somewhere?
import java.util.Scanner;
public class Homework4 {
public static void main(String[]args) {
// Sum and average of a set of intergers entered by the user
// First we will declare some variables
int userInput = 1;
int positives = 0;
int negatives = 0;
int sum = 0;
int numCount = 0;
Scanner input = new Scanner(System.in);
// Will start a while loop that will stop when user enters 20 integers
while ((numCount <= 20)) {
System.out.println("Please enter a nonzero integer or enter 0 to finish ");
userInput = input.nextInt();
if (userInput == 0) {
break;
} else if (userInput > 0) {
positives += 1;
numCount += 1;
sum = sum + userInput;
} else if (userInput < 0) {
negatives += 1;
numCount += 1;
sum = sum + userInput;
} else
System.out.println("Error, please enter an integer");
continue;
}
double average = (sum / numCount);
System.out.println("The sum of the entered integers is " + sum);
System.out.println("The average of the enetered integers is " + average);
System.out.println("There are " + positives + " positive integers and " + negatives + " negative integers");
// Convert Hexadecimal number to decimal
// Ask the user to input a string of 5 digits or less in hex
System.out.println("Please enter a hexadecimal number of up to 5 characters");
String hex = input.next();
if (hex.length() <= 5) {
System.out.println(hex + " in decimal value is equal to " + hexToDecimal(hex.toUpperCase()));
} else {
System.out.println("Error: please enter a hex number of 5 digits or less");
}
}
// Now we will create the method to convert to decimal
public static int hexToDecimal(String hex) {
int decimal = 0;
for (int i = 0; i < hex.length(); i++) {
char hexcharacter = hex.charAt(i);
decimal = decimal * 16 + hexCharToDecimal(hexcharacter);
}
return decimal;
}
public static int hexCharToDecimal(char ch) {
if (ch >= 'A' && ch <= 'F') // check to see if there is any letters in the string
return 10 + ch - 'A';
else
return ch - '0';
}
// Print entered integer in reverse
public static void intreverse(String[]args) {
// Ask user for an integer to be reversed
Scanner input = new Scanner(System.in);
System.out.println("Please enter an integer to be reversed");
int number = input.nextInt();
reverse(number); // Method to be called
}
// Will now state our method
public static void reverse(int number) {
// use a while loop to get each digit
while (number > 0) {
System.out.print(number % 10);
number = number / 10;
}
}
}
if (hex.length() <= 5) {
System.out.println(hex + " in decimal value is equal to " + hexToDecimal(hex.toUpperCase()));
} else {
System.out.println("Error: please enter a hex number of 5 digits or less");
}
Will always run once because it is not enclosed in any sort of loop. If you want it to run again when the second case is called then enclose it in a while(true) loop and have a break statement in the first case where you want it to stop execution.
I get an infinite loop every time I input the numbers 1, 3, 5 and I don't know how to fix it. This is a mastermind program using arrays in which pegs are used instead of numbers. The problem is most likely in the while loop in which was changed to make the program more condensed. Any help would be amazing.
package New;
import java.util.Random;
import New.ArrayMethod2;
import TurtleGraphics.KeyboardReader;
public class Mastermind2 {
public static void main(String[] args) {
Mastermind2 object = new Mastermind2();KeyboardReader reader = new KeyboardReader();
int[] V = new int [3];
do {
System.out.println("Please choose your first number (1-5)");
V[0]=reader.readInt();
System.out.println("Please choose your second number (1-5)");
V[1]=reader.readInt();
System.out.println("Please choose your third number (1-5)");
V[2]=reader.readInt();
}while((V[0]>5)&&(V[1]>5)&&(V[2]>5));
object.CorrectVariables(V[0], V[1], V[2]);
}
public void CorrectVariables(int num1, int num2, int num3) {
Mastermind1 object = new Mastermind1();
int Cornum1, Cornum2, Cornum3;
Random generator = new Random();
Cornum1 = generator.nextInt(5)+1;
Cornum2 = generator.nextInt(5)+1;
Cornum3 = generator.nextInt(5)+1;
IFstatements(Cornum1, Cornum2, Cornum3, num1, num2, num3);
}
public void IFstatements(int Cornum1, int Cornum2, int Cornum3, int num1, int num2, int num3) {
Mastermind1 object = new Mastermind1();
do{
int Number=0, Color=0;
if(Cornum1==num1)
{
Number++;
Color++;
}
if(Cornum1==num2)
{
Color++;
}
if(Cornum1==num3)
{
Color++;
}
if(Cornum2==num2)
{
Number++;
Color++;
}
if(Cornum2==num1)
{
Color++;
}
if(Cornum2==num3)
{
Color++;
}
if(Cornum3==num3)
{
Number++;
Color++;
}
if(Cornum3==num1)
{
Color++;
}
if(Cornum3==num2)
{
Color++;
}
System.out.println("You have "+Number+" numbers correct and "+Color+" colors correct");
if((Cornum1!=num1)||(Cornum2!=num2)||(Cornum3!=num3));
{
Number=0;
Color=0;
}
}while((Cornum1!=num1)&&(Cornum2!=num2)&&(Cornum3!=num3));
System.out.println("Congrats you guessed the correct numbers");
}
}
Print out:
It looks like the exit condition for your IFStatements function is that the user's input matches the correct pattern. However, the user does not get a chance to update his input and you never change the num or Cornum variables to match the correct output. Therefore, the loop is going to continue to execute forever. What you need to do is have that code run once and then give the user a chance to update their answers.
public static void main(String[] args) {
Mastermind2 object = new Mastermind2();
Scanner scan = new Scanner(System.in);
int one = getNumber("first", scan);
int two = getNumber("second", scan);
int three = getNumber("third", scan);
object.correctVariables(one, two, three);
}
private static int getNumber(String str, Scanner scan) {
while (true) {
System.out.print("Please choose your " + str + " number (1-5): ");
int num = scan.nextInt();
if (num >= 1 && num <= 5)
return num;
}
}
public void correctVariables(int one, int two, int three) {
Random random = new Random();
int expectedOne = random.nextInt(5) + 1;
int expectedTwo = random.nextInt(5) + 1;
int expectedThree = random.nextInt(5) + 1;
ifStatements(expectedOne, expectedTwo, expectedThree, one, two, three);
}
public void ifStatements(int expectedOne, int expectedTwo, int expectedThree, int one, int two, int three) {
int num = expectedOne == one ? 1 : 0;
num += expectedTwo == two ? 1 : 0;
num += expectedThree == three ? 1 : 0;
int color = expectedOne == one ? 1 : 0;
color += expectedOne == two ? 1 : 0;
color += expectedOne == three ? 1 : 0;
color += expectedTwo == one ? 1 : 0;
color += expectedTwo == two ? 1 : 0;
color += expectedTwo == three ? 1 : 0;
color += expectedThree == one ? 1 : 0;
color += expectedThree == two ? 1 : 0;
color += expectedThree == three ? 1 : 0;
System.out.println("You have " + num + " numbers correct and " + color + " colors correct");
if (num == 3)
System.out.println("Congrats you guessed the correct numbers");
}
My code is supposed to ask for a name, ask for a number between one and ten, print the numbers from 1 to the number the user entered except every third number should
be the user's name that was entered at the beginning of the program, print the even numbers, continually ask the user for numbers until the user enters the sentinel, and then print the total of the numbers entered. (I know, that's a lot.) My code is running fine, the only problem I am having is with the last part. Even when the user enters the sentinel, which in this case is -1, the program still asks for another entry.
Did I do something wrong when declaring the variable or can someone explain how to fix my problem? Here is my code.
import java.util.Scanner;
/**
*
* #author Home
*/
public class NewClass1 {
public static void main(String[] args) {
int number;
Scanner scan = new Scanner( System.in);
System.out.print( "Enter your name: ");
String name = scan.nextLine();
System.out.print( "Please enter a number between 1 and 10: ");
number = scan.nextInt();
//asks for a number between one and ten until I get number within that range,
while (number < 1 || number > 10) {
System.out.print( "No, between 1 and 10: ");
number = scan.nextInt();
}
for (int i = 1; i <= number; i++) {
if (i % 3 == 0) {
System.out.print(name + " ");
} else {
System.out.print(i + " ");
}
}
System.out.println();
for(int i =2; i<=number; i+=2)
System.out.print(i + " ");
System.out.print("are the even numbers.");
final int SENTINEL = -1;
int inputNumber;
int total = 0;
System.out.println(" Enter a number or -1 to finish. " );
inputNumber = scan.nextInt();
while ( inputNumber != SENTINEL )
{
total += number;
System.out.print("Enter the next number or '-1' to finish. ");
number = scan.nextInt();
}
System.out.println( "The total is " + total);
}
}
Solution:
You get input from user and saving that input in varible called number but you are checking your while against inputNumber.
while ( inputNumber != SENTINEL )
{
total += number;
System.out.print("Enter the next number or '-1' to finish. ");
inputNumber = scan.nextInt(); <<< not number should be inputNumber
}
public class NewClass1 {
public static void main(String[] args) {
int number;
Scanner scan = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scan.nextLine();
System.out.print("Please enter a number between 1 and 10: ");
number = scan.nextInt();
//asks for a number between one and ten until I get number within that range,
while (number < 1 || number > 10) {
System.out.print("No, between 1 and 10: ");
number = scan.nextInt();
}
for (int i = 1; i <= number; i++) {
if (i % 3 == 0) {
System.out.print(name + " ");
} else {
System.out.print(i + " ");
}
}
System.out.println();
for (int i = 2; i <= number; i += 2) {
System.out.print(i + " ");
}
System.out.print("are the even numbers.");
final int SENTINEL = -1;
int inputNumber;
int total = 0;
do {
System.out.println(" Enter a number or -1 to finish. ");
inputNumber = scan.nextInt();
if(inputNumber!= SENTINEL){
total+=inputNumber;
}
} while (inputNumber != SENTINEL);
System.out.println("The total is " + total);
}
}
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());
}
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)