Having trouble with this code that am I writing. The purpose of the code is to formulate modifiers for a number sequence and then give the first 10 numbers in that sequence. However, something appears to be wrong with my loop mechanism because it is printing out an infinite amount of values when it should only be doing 10. I plan on including the division and power functions to the code, but ran into this problem.
import java.util.Scanner;
public class PatternCreator {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out
.println("Please enter the starting value of the number sequence.");
double sequence = s.nextInt();
System.out
.println("Please enter the addition/subtraction modifier; e.g. 2,-2.");
double addsub = s.nextInt();
System.out
.println("Please enter the multiplication modifier; 0 for none.");
double mult = s.nextInt();
System.out.println("Please enter the division modifier; 0 for none.");
double divi = s.nextInt();
System.out
.println("Please enter the exponential modifier; 0 for none.");
double power = s.nextInt();
double addonly = sequence + addsub;
while (mult == 0 && divi == 0 && power == 0) {
for (int count1 = 1; count1 <= 10; count1++) {
if (count1 == 1) {
System.out.print(sequence + " ");
} else {
System.out.print(addonly + " ");
addonly = addonly + addsub;
}
}
}
double multadd = sequence + addsub * mult;
while (mult != 0 && divi == 0 && power == 0) {
for (int count2 = 1; count2 <= 10; count2++) {
if (count2 == 1) {
System.out.print(sequence + " ");
} else {
System.out.print(multadd + " ");
multadd += multadd;
}
}
}
}
}
Sounds like mult, divi, and power are all 0, and you never change them-- therefore you're executing your while loop (and therefore your for loop) an infinite number of times.
Why do you have that while loop there at all?
You never, ever, change the values of multi, divi or power. How do you expect the while to end if those values never change?
Related
I am new to java and I was learning how to convert from binary to decimal and vice versa. In the case of binary to decimal, I found out that I could use parseint, but I saw other methods that didn't use it, so I tried to implement them into my code, but it didn't work for me and I got stumped.
How would I be able to use a different method for calculating binary to decimal and implement it into my code?
Here is my code:
import java.util.Scanner;
class BinaryToDecimal {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String binaryString;
char choice;
String nextLine = "Empty";
int i = 0;
choice = 'Y';
try {
do {
System.out.print("Enter a binary number: ");
binaryString = sc.nextLine();
//Find the string count
int count = binaryString.length();
for (int j = 0; j< count; j++)
{
if (binaryString.charAt(j) != '1' && binaryString.charAt(j) != '0')
{
System.out.print("Enter a binary number: ");
binaryString = sc.nextLine();
count = binaryString.length();
j=0;
}
}
i = Integer.parseInt(binaryString);
if (i>0)
System.out.println("The decimal number is: " + Integer.parseInt(binaryString, 2));
System.out.println("Continue using the calculator? Only input Y or N");
String ln = sc.next();
if(ln.length()==1){
choice = ln.charAt(0);
}
else{
choice = 'N';
}
if (sc.hasNextLine()) {
nextLine = sc.nextLine();
}
} while (choice == 'Y');
} catch (NumberFormatException nfe) {
System.out.println("Invalid input");
}
}
}
Binary math involves adding 1 and multiplying by 2. I would use a regular expression to test if the input is valid. I would use an infinite loop and break when the user gives an answer besides y when prompted to continue. Putting that together, gives a simplified
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter a binary number: ");
String binaryString = sc.nextLine();
// An int value consists of up to 32 0 and 1s.
if (!binaryString.matches("[01]+") || binaryString.length() > 32) {
continue;
}
int v = 0;
for (int i = 0; i < binaryString.length(); i++) {
v *= 2;
if (binaryString.charAt(i) == '1') {
v++;
}
}
System.out.println("The decimal number is: " + v);
System.out.println("Continue using the calculator? Only input Y or N");
String ln = sc.nextLine();
if (!ln.equalsIgnoreCase("Y")) {
break;
}
}
It looks like your missing you're missing the radix which the default I use is 2. Try this and let me know what happens
i = Integer.parseInt(binaryString,2);
There may be a nicer way of doing this, however this is the solution that I came up with. I took into account that the number can both be a positive and negative number and added checks for those cases. I also made sure to add exceptions for when an invalid binary number is entered.
public static int numberFromBinary(String binaryNumber) {
char[] array = binaryNumber.toCharArray();
boolean isNegative = false;
int result = 0;
if (array.length > 32) {
throw new NumberFormatException("An integer cannot be more than 32 bits long.");
}
if (array.length == 32) {
isNegative = array[0] == '1';
if (isNegative) {
result -= 1;
}
}
for (int i = 0; i < array.length && i != 31; i++) {
int worth = (int) Math.pow(2, i);
if (array[array.length - 1] != '1' && array[array.length - 1] != '0') {
throw new NumberFormatException("Binary bits can only be a '1' or a '0'.");
}
if (isNegative) {
if (array[array.length - 1] == '0') {
result -= worth;
}
} else {
if (array[array.length - 1] == '1') {
result += worth;
}
}
}
return result;
}
Here's a solution for converting a string representation of a binary number to a decimal number, without using Integer.parseInt(). This is based on
your original question text:
How would I be able to use a different method for calculating binary to decimal and implement it into my code?
And also a comment you added:
Also i did not want to use parseint
If you take a binary number and work your way from right to left, each digit is an increasing power of 2.
0001 = 2^0 = 1
0010 = 2^1 = 2
0100 = 2^2 = 4
1000 = 2^3 = 8
You can follow this same pattern: inspect each character position of a binary string input, and raise 2 to some power to get the decimal value represented by that bit being set to 1. Here's a simple bit of code that:
prompts for user input as a binary string
starting from right and working toward the left, it checks each character, comparing against '1'
if the character is in fact 1: take note of the position, raise 2 to the next power, and add that to the running total
Here's the code:
System.out.print("enter a binary number: ");
String binaryInput = new Scanner(System.in).next();
int decimalResult = 0;
int position = 0;
for (int i = binaryInput.length() - 1; i >= 0; i--) {
if (binaryInput.charAt(i) == '1') {
decimalResult += Math.pow(2, position);
}
position++;
}
System.out.println(binaryInput + " --> " + decimalResult);
And a few sample runs:
enter a binary number: 1111
1111 --> 15
enter a binary number: 101010101
101010101 --> 341
enter a binary number: 100000000000
100000000000 --> 2048
import java.util.Scanner;
public class Swap {
// if the number is less than 10, swap the last two numbers and print them.
public static void main(String[] args) {
// User to enter a number between 1 and 10, but not zero.
Scanner number = new Scanner(System. in );
System.out.println("Enter a Integer(whole number) between 1 and 10. : ");
int userNum = number.nextInt();
while (userNum > 10 || userNum < 0) {
System.out.println("Try again: ");
userNum = number.nextInt();
}
System.out.println("Your number loop");
while (userNum <= 10) {
System.out.println(userNum);
userNum++;
}
System.out.println("Guess the two swap numbers:");
}
}
How do I swap the last two numbers? I am a beginner learning java and OOP. I have created this program where the user has to enter a number between 1 and 10. If the user enters a number below 1 and above 10, the user gets prompted to try again. Then it prints the list of numbers based off the users input. e.g. if the user enters 8, its prints the loop 8,9 and 10. I have having trouble, I understand how to swap two variable, not inside a loop. Thank you and much appreciated for your help.
Let's assume that the maximum number is a parameter N, so that you could swap any last two numbers and place N before N - 1
private static final int N = 10;
There are several ways to do this using different Java operators:
if, to update delta parameter
while (userNum <= N) {
int delta = 0;
if (userNum >= N - 1) {
delta = userNum == N - 1 ? 1 : -1;
}
System.out.println(userNum + delta);
userNum++;
}
or simply skip N - 1 and print it after the loop:
while (userNum <= N) {
if (userNum != N - 1) {
System.out.println(userNum);
}
userNum++;
}
System.out.println(N - 1);
switch
while (userNum <= N) {
int printNum = userNum++;
switch(printNum) {
case N:
printNum--; break;
case N - 1:
printNum++; break;
default:
break;
}
System.out.println(printNum);
}
two consequent loops (the second going backwards):
while (userNum < N - 1) {
System.out.println(userNum++);
}
userNum++;
while (userNum >= N - 1) {
System.out.println(userNum--);
}
another way this can be solved is by creating a loop(for or while) and taking the two numbers you can use the math functions- Math.max(a,b) || Math.min(a,b) to find the biggest and smallest numbers. Afterwards you can create more variables- c&d to save the two numbers.
goodluck
a=max
b=min
then
c=a
d=b;
then a=d and b=c.
I'm making a program where you put in two integers, and the program finds the greatest common divisor between the two numbers.
It runs fine, except it prints "1" as the GCD, even when the two numbers should have a different GCD. (Example: 4 & 64. GCD should be 4, but 1 still gets printed.) I can't figure out what's wrong with my code.
For those who want to answer using one method instead, I can't: It's an assignment that requires me to use two different methods in the same program. Please help?
Thanks for reading, and have a good week.
Here my code:
import java.util.Scanner;
public class greatestCommonDivisorMethod {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
//Number entry prompts
System.out.print("Please enter first integer: ");
int num1 = input.nextInt();
System.out.print("Please enter second integer: ");
int num2 = input.nextInt();
//Result printed
System.out.println("The greatest common divisor of " +num1+ " and " +num2+ " is " +gcd(num1, num2)+".");
}
public static int gcd(int num1, int num2) {
int gcd = 1;
int k = 2;
while (num1 <= k && k <= num2)
{
if (num1 % k == 0 && num2 % k == 0)
gcd = k;
k++;
}
return gcd;
}
}
while (num1 <= k && k <= num2)
{
if (num1 % k == 0 && num2 % k == 0)
gcd = k;
k++;
}
It looks like you accidentally switched num1 and k in your while loop.
The while condition should probably have k<=num1 instead of num1<=k
Assign your return to a variable then print it
int answer = gcd(num1, num2);
then when printing cast to String or use toString method.
System.out.println("The greatest common divisor of " +answer.toString());
I don't understand why only my while statement is working and it does not move on to the for statement for the valid integer.
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
long posNumber;
long x;
long fact = 1;
do {
System.out.print("Enter a number between 2 and 15: ");
Scanner in = new Scanner(System.in);
posNumber = in.nextLong();
} while (posNumber >= 2 || posNumber <= 15);
for (x = 1; x <= posNumber; x++)
fact = fact*x;
System.out.println("Factorial of " +posNumber+ " is " +fact);
}
}
You should try something like, if you plan to get numbers in a loop:
Scanner in = new Scanner(System.in);
do {
System.out.print("Enter a number between 2 and 15: ");
posNumber = in.nextLong();
for (x = 1; x <= posNumber; x++)
fact = fact*x;
System.out.println("Factorial of " +posNumber+ " is " +fact);
}
} while (posNumber >= 2 || posNumber <= 15);
Or you can change the condition (in case to run it just once):
while (posNumber < 2 || posNumber > 15);
You want your program to continue asking the user if the number is invalid. That means if it is less than 2 or greater than 15. Replace your while condition with:
do {
...
} while (posNumber < 2 || posNumber > 15);
If the user enters a 1, posNumber < 2 will evaluate to true causing the loop to repeat and ask for a new number.
If the user enters 3, both posNumber < 2 and posNumber > 15 will evaluate to false and the loop will break and then your for loop will execute.
Can not for the life of me figure out why my average is not displaying correctly I've looked at it for like 2 hours.
import java.util.Scanner;
public class midterm
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int examScore =0;
int averageExamScore = 0;
int numStudent=0;
int sum=0;
while(examScore >= 0)
{
System.out.println("Enter exam scores (enter negative number to quit): ");
examScore = keyboard.nextInt();
numStudent++;
sum = sum + examScore;
}
if(numStudent > 0)
{
averageExamScore = sum/numStudent;
}
else
{
System.out.println("No scores to average");
}
}
}
The issue here is integer division.
averageExamScore = sum/numStudent;
All three of these arguments are integers, which means:
If you cast a part of your quotient to double, you'd lose precision (and fail compilation)
Example:
averageExamScore = (double)sum/numStudent; // wouldn't compile
The floor of the quotient sum/numStudent is provided instead of the whole number (so for a number like 4.9 you'd get 4).
You can fix this in a few ways:
Declare averageExamScore to be a double. This is required.
Either cast sum or numStudent to a double, or change their type to double.
You have defined averageExamScore as an integer, so integer arithmetic will be applied.
e.g.
5 / 2 == 2
1 / 2 == 0
Make averageExamScore into a double, and also cast your other integers to doubles.
Edit
To print out
do
if(numStudent > 0)
{
averageExamScore = sum/numStudent;
System.out.println ("average score is " + averageExamScore );
}
Go through the following code,
public class MidTerm {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int examScore = 0;
double averageExamScore = 0;
int numStudent = 0;
int sum = 0;
while (true) {
System.out.print("Enter exam scores (enter negative number to quit): ");
examScore = keyboard.nextInt();
if (examScore >= 0) {
numStudent++;
sum += examScore;
} else break;
}
if (numStudent > 0) {
averageExamScore = sum / numStudent;
System.out.println("Avarage score is : " + averageExamScore);
} else System.out.println("No scores to average");
}
}
averageExamScore variable should be a double otherwise it can not stored floating point values
Good Luck !!!