Write a program that reads integers from the user until he enters -1, and print “Consecutive ” if there are three consecutive numbers otherwise print “None Consecutive”; that is in the number list you read are in an order such that there is some integer k that the numbers values are k, k+1, and k+2.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int y = x + 1;
int z = x + 2;
boolean areConsecutive = false;
while (x != -1) {
if (x == y) {
x = scan.nextInt();
if (x == z)
areConsecutive = true;
}
x = scan.nextInt();
}
if (areConsecutive)
System.out.print("Consecutive");
else
System.out.print("None Consecutive");
}
Can anyone please tell me what's wrong with this code?
Get the next integer before checking with y, then check for z. if one of these fails update y and z and check again.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int y = x + 1;
int z = x + 2;
boolean areConsecutive = false;
while (x != -1) {
x = scan.nextInt();
if (x == y) {
x = scan.nextInt();
if (x == z)
areConsecutive = true;
}
y = x + 1;
z = x + 2;
}
if (areConsecutive)
System.out.print("Consecutive");
else
System.out.print("None Consecutive");
}
You need to increment y and z by 1 before scaning new x.
This is what you are looking for:
Scanner scan = new Scanner(System.in);
System.out.println("enter");
int x = scan.nextInt();
boolean areConsecutive = false;
while (x != -1) {
int y = x + 1;
System.out.println("enter");
x = scan.nextInt();
if (x == y) {
System.out.println("enter");
int z = x + 1;
x = scan.nextInt();
if (x == z)
areConsecutive = true;
}
}
if (areConsecutive)
System.out.println("Consecutive");
else
System.out.println("None Consecutive");
You're close but you're not maintaining the history of the numbers correctly.
First, to clarify, the specification calls for you to enter an arbitrary quantity of arbitrary numbers from the user and simply check if any three of them are consecutive. Hence the first line below would have a consecutive sequence (the 1 2 3 bit starting at the third number) but the second would not:
9 9 1 2 3 9
3 1 4 1 5 9
One way to do this is simply maintain the minimal information to detect a consecutive sequence. To do that, you need to keep a copy of only the last three numbers entered. The pseudo-code (easily transformable into any procedural language) for such a beast would be:
# Get first number, ensure no chance of consecutive
# sequence until at least three are entered.
num3 = getint()
num2 = num3
num1 = num3
consecutive = false
# Loop until -1 entered.
while num3 != -1:
# Check for consecutive sequence.
if (num1 + 1 == num2) and (num2 + 1 == num3):
consecutive = true
# Shift numbers "left".
num1 = num2
num2 = num3
num3 = getint()
if consecutive:
print "Consecutive"
else
print "None Consecutive"
This is what you are looking for:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int y = scan.nextInt();
int z = scan.nextInt();
boolean areConsecutive = false;
while ((x != -1)&&(y != -1)&&(z != -1)){
if ((z == y + 1)&&(y == x + 1)
areConsecutive = true;
if (areConsecutive)
System.out.print("Consecutive");
else
System.out.print("None Consecutive");
}
I would do it this way, we have to check if three numbers are consecutive no matter the order they were entered by user:
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int[] numbers = new int[3];
for( int i = 0; i < numbers.length; ++i)
numbers[i] = scan.nextInt();
Arrays.sort(numbers);
boolean areConsecutive = true;
for( int i = 0; i < numbers.length - 1; ++i)
if(numbers[i+1] - numbers[i] != 1)
areConsecutive = false;
if(areConsecutive)
System.out.print("Consecutive");
else
System.out.print("None Consecutive");
}
Related
public class ProductOfDigits {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int n = input.nextInt();
int x = Math.abs(n);
int product = 1;
if (x >=0 && x<=9) {
System.out.println(x);
}
else {
product = product * (x % 10);
x = x/10;
System.out.println(product);
}
When the input is negative number, the product is between first and last digit. Can anyone explain? I have tried Math.abs() to get absolute value but it is impossible and it is killing me now.
Do it as follows:
import java.util.Scanner;
public class ProductOfDigits {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int n = input.nextInt();
int x = Math.abs(n);
int ç = 1;
int product = 1;
if (x == 0) {
product = 0;
} else {
while (x > 0) {
product *= x % 10;
x /= 10;
}
}
System.out.println(product);
}
}
Sample run-1:
Enter an integer: -256
60
Sample run-2:
Enter an integer: 0
0
Sample run-3:
Enter an integer: 9
9
Sample run-4:
Enter an integer: 256
60
Recursive version:
import java.util.Scanner;
public class ProductOfDigits {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int n = input.nextInt();
System.out.println(productOfDigits(n));
}
static int productOfDigits(int n) {
n = Math.abs(n);
if (n > 0 && n < 10) {
return n;
}
if (n == 0) {
return 0;
}
return (n % 10) * productOfDigits(n / 10);
}
}
You can use Math.log10() function from java to get the number of your digits and then calculate the first digit based on it:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = input.nextInt();
if (number < 0) {
number *= (-1);
}
int digits = (int) Math.log10(number);
int lastDigit = number % 10;
int firstDigit = (int) (number / Math.pow(10, digits));
int product = lastDigit * firstDigit;
System.out.println(product);
}
And of course, if your number is negative, you can use Math.abs() (instead of if)
Your current code only prints out the last digit of the entered integer because you are only doing product = product * (x % 10); (can be simplified to product *= x % 10;) and x = x / 10; (can be simplified to x /= 10;) once each. You should repeatedly do these two operations until x is 0.
You could use a for loop or a while loop for this. Here's how to write this with a for loop:
for (; x > 0 ; x /= 10) {
product *= x % 10;
}
The condition for the if statement can also be changed to just x == 0, as the x values 1-9 can all be correctly handled by the else clause.
I want my code to loop, but reinitialize the variable back to 0. Every time I input a number, it add it to the previous result, but I want it to reset. I attached two images below. One is the actual output and the other is the expected output.
import java.util.Scanner;
public class AddOrMultiplyNNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String am;
int sum = 0;
int total = 1;
int n = 0;
while (true) {
System.out.print("enter an integer number: ");
n = input.nextInt();
if(n == 0) {
break;
}
System.out.print("enter either 'a' or 'm': ");
input.nextLine();
am = input.nextLine();
if (am.equals("a")) {
for (int y = 1; y <= n; y++) {
sum = sum + y;
}
System.out.println(sum);
} else if (am.equals("m")) {
for (int x = 1; x <= n; x++) {
total = total * x;
}
System.out.println(total);
}
}
}
}
Actual Output
Desired Output
You can use continue
if(n == 0) {
sum = 0;
total = 1;
continue;
}
You can initialize the variables inside the while loop
public class AddOrMultiplyNNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String am;
while (true) {
int sum = 0;
int total = 1;
int n = 0;
System.out.print("enter an integer number: ");
n = input.nextInt();
if(n == 0) {
break;
}
System.out.print("enter either 'a' or 'm': ");
input.nextLine();
am = input.nextLine();
if (am.equals("a")) {
for (int y = 1; y <= n; y++) {
sum = sum + y;
}
System.out.println(sum);
} else if (am.equals("m")) {
for (int x = 1; x <= n; x++) {
total = total * x;
}
System.out.println(total);
}
}
}
}
To zero a variable, simply assign 0 at the appropriate point.
sum = 0;
An appropriate place to insert this statement for your desired output is immediately before the first for loop. Likewise, reset total before the second for.
However, a much better way to write this is to declare the variable where it is needed, as you have done for x and y. This applies to am, sum, total and n
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("enter an integer number: ");
int n = input.nextInt();
if (n == 0) {
break;
}
System.out.print("enter either 'a' or 'm': ");
input.nextLine();
String am = input.nextLine();
if (am.equals("a")) {
int sum = 0;
for (int y = 1; y <= n; y++) {
sum = sum + y;
}
System.out.println(sum);
} else if (am.equals("m")) {
int total = 1;
for (int x = 1; x <= n; x++) {
total = total * x;
}
System.out.println(total);
}
}
I don't know if I fully understand your question, but just do sum=0; and total=1; after you print out the final result. You should also consider doing a try/catch statement for robustness on the nextInt so that characters and strings don't break your program...
try {
n = input.nextInt();
}
catch (Exception e) {
System.out.println("Not a Number");
}
This is the instructions.
Write a program that reads a sequence of input values and displays a bar chart of the values using asterisks. You may assume that all values are positive. First figure out the maximum value. That's value's bar should be drawn with 40 asterisks. Shorter bars should use proportionally fewer asterisks.
This is what I came up so far. It's all good except I need to enter a letter instead of a negative number to quit scanning. I have tried (if( < 0) things) but those didn't work.
import java.util.Scanner;
public class BarChart1 {
public static void main(String [] args) {
int[] arr = new int[100];
int currentSize = 0;
System.out.println("Enter a sequence of positive integers. "
+ ("Enter a negative value to quit:"));
Scanner in = new Scanner(System.in);
while(in.hasNextInt()) {
int num = in.nextInt();
if (num < 0) {
break;
}
else {
arr[currentSize] = in.nextInt();
currentSize++;
}
}
//will find the max
double max = arr[0];
int y = 0;
for (int i = 1; i < arr.length; i++) {
y = i + 1;
if(max < arr[i]) {
max = arr[i];
//y = i + 1;
}
}
System.out.println("Max number is: " + max);
System.out.println("Number of digits = " + y);
System.out.println(Math.abs(-1));
double scale = 40/max;
System.out.println("Scale = " + scale);
for (int i = 0; i < y; i++) {
double h = scale * arr[i];
if (h != 0) {
for (int j = 1; j <= h; j ++) {
System.out.print("*");
}
System.out.println();
}
}
}
}
This is the result.
1
2
3
4
-1
Max number is: 4.0
Number of digits = 100
Scale = 10.0
********************
****************************************
I only need the asterisks. Everything else that is being printed is just for checking purposes.
You can try this:
while(in.hasNextInt()) {
int num =in.nextInt();
if(num <0){
break;
}
else{
arr[currentSize] = num;
currentSize++;
}
}
I'm supposed to write a program in java, that allows the user to determine number (quantity) of prime numbers, that he wants to be displayed.
I have managed to write a program, in which user can specify the maximum prime number.
Can I please have some tips?
import java.util.Scanner;
public class PrimeNumbers{
public static void main(String[] agrs){
int max;
Scanner sk = new Scanner(System.in);
System.out.print("How many prime numbers you want to display? ");
max = sk.nextInt();
System.out.print("Prime numbers: ");
for(int x =2; x <= max; x++){
boolean isPrime = true;
for(int y = 2; y < x; y++){
if(x % y == 0){
isPrime = false;
break;
}
}if (isPrime){
System.out.print(x + " ");
}
} System.out.print("...");
}
}
If i.e I put as a user 5, I get only 2,3, 5
But I want the result to be: 2, 3, 5, 7, 11
Track the number of primes you have printed, which is not x. Check whether you have printed enough.
import java.util.Scanner;
public class PrimeNumbers{ public static void main(String[] agrs){
int max;
int numPrinted=0;
Scanner sk = new Scanner(System.in);
System.out.print("How many prime numbers you want to display? ");
max = sk.nextInt();
System.out.print("Prime numbers: ");
for(int x =2; numPrinted < max; x++){
boolean isPrime = true;
for(int y = 2; y < x; y++){
if(x % y == 0){
isPrime = false;
break;
}
}if (isPrime){
System.out.print(x + " ");
numPrinted++;
}
} System.out.print("...");
} }
import java.util.Scanner;
public class Rpn_calculator
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
double ans = 0;
double n = 0;
double r = 0;
String j;
System.out.println();
System.out.println();
System.out.print("Please enter a value for n ");
n = keyboard.nextDouble();
System.out.print("Please enter a value for r ");
r = keyboard.nextDouble();
System.out.println("Please choose one of these operands:+,-,*,nCr,/ to continue, or q to quit ");
j = keyboard.nextLine();
while (j != "q")
{
if(j == "+")
ans = n + r;
if(j == "-")
ans = n - r;
if(j == "*")
ans = n * r;
if(j == "/")
ans = n / r;
if(j == "nCr")
ans = factorial(n + r -1) / (factorial(r)*factorial(n - 1));
System.out.print(ans);
System.out.print("Please enter a value for n ");
n = keyboard.nextDouble();
System.out.print("Please enter a value for r ");
r = keyboard.nextDouble();
System.out.print("Please choose one of these operands:+,-,*,nCr,/ to continue or q to quit ");
j = keyboard.nextLine();
}
}
public static double factorial(double x);
{
double sum = 1;
int i;
for (i = 0; i<= x; i++);
sum = sum * i;
return sum;
}
}
I am trying to create an RPN calculator for this assignment, I believe I have what I need to make it function, but I have syntax errors with my factorial function. It says "missing method body".
Also, I don't understand why, when I compile it, my string input request is ignored completely - locking the program in the while loop. I hope I'm not missing something really obvious.
There are a couple of semicolons where there shouldn't be:
public static double factorial(double x); // <-- This one
{
double sum = 1;
int i;
for (i = 0; i<= x; i++); // <-- This one
sum = sum * i;
return sum;
}
When you put the semicolon right after the signature, you have no method body, hence the error. The for loop wouldn't be a compiler error, but it would be an empty loop.
Also, I think you need to use String.equals to compare strings in Java, as opposed to the == operator.