I'm trying to make a program that generates random two-digit integers until I get a 10 or a 20. To then find the mount of numbers, the sum of the numbers less than 10, the sum of the numbers equal to 15, the sum of the numbers greater than 70. Can someone help me, please?
This is my code:
// Variables
int numRandom = 0, less10, equal15, more70;
// Process
txtS.setText("Random numbers: " + "\n");
for (int mountNum = 0; numRandom == 40 || numRandom == 20; mountNum++) {
numRandom = (int) (99 * Math.random());
txtS.append(numRandom + "\n");
}
You could just store the values directly and create variables for each case.
This is an example for you less than 10 case. (The 'if statement' would be contained inside your for loop).
int sumLessThanTen = 0;
int countLessThanTen = 0;
...
if(numRandom < 10){
sumLessThanTen += numRandom;
countLessThanTen++
}
Related
For this lab, you will enter two numbers in base ten and translate
them to binary. You will then add the numbers in binary and print out
the result. All numbers entered will be between 0 and 255, inclusive,
and binary output is limited to 8 bits. This means that the sum of the
two added numbers will also be limited to 8 bits. If the sum of the
two numbers is more than 8 bits, please print the first 8 digits of
the sum and the message "Error: overflow". Your program should
represent binary numbers using integer arrays, with the ones digit
(2^0) stored at index 0, the twos digit (2^1) stored at index 1, all
the way up to the 2^7 digit stored at index 7. Your program should
include the following methods:
int[] convertToBinary(int b) Translates the parameter to a binary value and returns it stored as an array of ints.
void printBin(int b[]) Outputs the binary number stored in the array on one line. Please note, there should be exactly one space
between each output 0 or 1.
int[] addBin(int a[], int b[]) Adds the two binary numbers stored in the arrays, and returns the sum in a new array of ints.
When entering my code into CodeRunner (which tests the code and returns a grade back depending on the results of each test) I cannot seem to pass one of the tests. This is the message that I am getting:
*You had 43 out of 44 tests pass correctly. Your score is 97%.
The tests that failed were: Test: addBin() method Incorrect: Incorrect number returned*
Heres my code:
import java.util.Scanner;
class Main {
public static int[] convertToBinary(int a) {
int[] bin = {0, 0, 0, 0, 0, 0, 0, 0};
for (int i = bin.length - 1; i >= 0; i--) {
bin[i] = a % 2;
a = a / 2;
}
return bin;
}
public static void printBin(int[] b) {
int z;
for (z = 0; z < b.length; z++) {
System.out.print(b[z] + " ");
}
System.out.println();
}
public static int[] addBin(int[] c, int[] d) {
int[] added = new int[8];
int remain = 0;
for (int x = added.length - 1; x >= 0; x--) {
added[x] = (c[x] + d[x] + remain) % 2;
remain = (c[x] + d[x] + remain) / 2;
}
if (added[0] + c[0] + d[0] == 1) {
added[0] = 1;
} else if ((added[0] + c[0] + d[0] == 2) || (added[0] + c[0] + d[0] == 3)) {
System.out.println("Error: overflow");
}
return added;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a base ten number between 0 and 255, inclusive.");
int num1 = scan.nextInt();
System.out.println("Enter a base ten number between 0 and 255, inclusive.");
int num2 = scan.nextInt();
int[] bin;
bin = convertToBinary(num1);
System.out.println("First binary number:");
printBin(bin);
int[] bin1 = bin;
bin = convertToBinary(num2);
System.out.println("Second binary number:");
printBin(bin);
int[] bin2 = bin;
System.out.println("Added:");
{
printBin(addBin(bin1, bin2));
}
}
}
If anyone could take a look at my code above and see if they could tell me what needs to be changed to fix the addbin() method so that it passes all of the tests, that'd be great! Any help is greatly appreciated even if you are not sure it would work! Thanks!
Hi first of all pardon my English but i guess your assignment accepts 1 and 255 too. So i added two of them and get 1 0 0 0 0 0 0 0 in your code. But i think it need to be 0 0 0 0 0 0 0 0 with an overflow error. So i changed your code a little bit.
public static int[] addBin(int[] c, int[] d) {
int[] added = new int[8];
int remain = 0;
for (int x = added.length - 1; x >= 0; x--) {
added[x] = (c[x] + d[x] + remain) % 2;
remain = (c[x] + d[x] + remain) / 2;
}
if (remain!=0) {
System.out.println("Error: overflow");
}
return added;
}
It's my first answer on the site so i hope it works for your test
The Word Problem I'm trying to solve:
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
I'm sure you've seen questions about this problem on Project Euler before, but I'm not sure why my solution doesn't work, so I'm hoping you can help!
public class Problem2Fibonacci {
public static void main(String[] args) {
/* Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. */
int sum = 0; // This is the running sum
int num1 = 1; // This is the first number to add
int num2 = 2; // This is the second number
int even1 = 0;
int even2 = 0;
int evensum = 0;
while (num2 <= 4000000){ // If i check num2 for the 4000000 cap, num will always be lower
sum = num1 + num2; // Add the first 2 numbers to get the 3rd
if(num2 % 2 == 0){ // if num2 is even
even1 = num2; // make even1 equal to num2
}
if(sum % 2 == 0){ // if sum is even
even2 = sum; // make even2 equal to sum
}
if (even1 != 0 && even2 != 0){ // If even1 and even2 both have values
evensum = even1 + even2; // add them together to make the current evensum
even2 = evensum;
}
num1 = num2;
num2 = sum;
System.out.println("The current sum is: " + sum);
System.out.println("The current Even sum is: " + evensum);
}
}
}
So my 2 questions are,
1. Why doesn't my plan to get sum of even numbers work correctly?
and
2. The last time my loop runs, it uses a num2 that is > 4000000. Why?
Thanks!
This should help you :
int first = 0;
int second = 1;
int nextInSeq =first+second;
int sum =0;
while(nextInSeq < 4000000) {
first = second;
second = nextInSeq;
nextInSeq = first + second;
if(nextInSeq % 2 ==0)
sum = sum + nextInSeq;
System.out.println("Current Sum = " + sum);
}
System.out.println("Sum = " + sum);
For your piece of code : even1 and even2 are not required and they are carrying value they hold from previous iterations as you continue.
I want this while loop to print every multiple of two below the number submitted(ex. if 100 was submitted it would print 2 4 8 16 32 64). Here's what I have(I'm only going to include a portion of the class because there was other things in it that don't pertain to this part)
i = 1;
Scanner myScanner = new Scanner(System.in);
System.out.print("Would thoughst be inclined to enter a number fair sir/madam: ");
String answer = myScanner.nextLine();
int number = Integer.parseInt(answer);
System.out.print("Your number set is: ");
while(i <= number)
{
i = 2*i;
System.out.print(" " + i + " ");
}
What this prints if I enter 100 is: 2 4 8 16 32 64 128
How do I get rid of that last number?
You would get rid of that number by modifying your logic to match. Your code is doing precisely what it says. One option is to start at 2, and increase i at the end of the loop instead of just before printing it. You could also use a for loop:
for (int i = 2; i < 100; i *= 2)
...
If you want to save the last power, you have a few options, e.g.:
int k = 2;
for (int i = k; i < 100; i *= 2) {
k = i;
...
}
Or undo the last operation:
int i;
for (i = 2; i < 100; i *= 2)
...;
i /= 2;
Or check the next one:
int i;
for (i = 2; i * 2 < 100; i *= 2)
...;
Checking the next one, in your original form:
while (i * 2 <= number)
...;
Etc.
By the way, your title says "factors", your description says "multiples", and your code says "powers"...
In your code
while(i <= number)
{
i = 2*i;
System.out.print(" " + i + " ");
}
the problem is that i, when it is equal to 64, is indeed less than 100, so the loop continues.
If you change it to
i = 2*i;
while(i <= number)
{
System.out.print(" " + i + " ");
i = 2*i;
}
it does as you wish, because it pre-computes the value before being analyzed as the while-loop terminator.
Try
while( i <= number / 2)
Those are powers of 2, not factors of 2.
"thoughst" is not a word. It should be "thou".
Update the value of i after you print it.
I am writing a program to print out a user inputed integer into binary form.
When I run it and input, say the number 5, it crashes and gives me the error:
java.lang.ArrayIndexOutOfBoundsException: 30
at PrintBinaryDigitsFixed.main(PrintBinaryDigitsFixed.java:27)
i.e the line "digits[counter] = number % 2;"
Why am I getting an out of bounds exception? It should assign the remainder to the first element then move on to the second shouldn't it?
I feel like I'm making a glaringly obvious mistake but I can't tell what it is
final int MIN = 0;
final int MAX = (int) (Math.pow(2, 30) - 1);
int[] digits = new int[30]; //array to hold the digits
int number = readInput
("Enter an integer from " + MIN + " to " + MAX, MIN, MAX);
int counter = 0;
int modNumber = 2;
while(modNumber / 2 != 0)
{
digits[counter] = number % 2;
modNumber = number / 2;
counter++;
}
System.out.print(number + " in binary form is ");
listBackwardsFrom(digits, counter);
Thanks
You never change number in your loop, and you assign modNumber = number / 2 in the loop, so from the second iteration onward modNumber is a constant (for most of the first iteration it's 2, but then you assign number / 2 to it); if you reach that point at all, you'll stay there. So the loop continues until counter reaches 30, at which point digits[counter] throws the exception.
I am trying to write a simple and quite useless program to generate a list of all integers 1><1000 where the sum of digits is 11. Every time I run this, I end up in an infinite loop. I've tried different things - for(){}, while(){}, adding a if(count>500){break;} to halt it after the loop counter reaches 500....still nothing...where am I going wrong in this?
Thanks in advance
//loops through all numbers whose sum of digits is 11
for(int number = 29; number < 1000; number++) {
//checks the values of the 100,10,and 1 position
int hPlace = number / 100; number = number - (hPlace * 100);
int tPlace = number / 10; number = number - (tPlace * 10);
int oPlace = number;
//sum of digits
int i = hPlace + tPlace + oPlace;
//prints if sum of digits is 11
int count = 0;
if (i == 11) {
count++;
System.out.print(i + " ");
}
//new line after every 10 numbers -- just for formatting
if (count % 10 == 0) {
System.out.println("");
}
}
You are using same variable as controller for your fors. Try to change the controller variable within the for structure from number to number1
You are changing the variable here:
---------------------------------
int hPlace = number / 100; number = number - (hPlace * 100);
---------------------------------
Don't do this
number = number - (hPlace * 100);
when your condition is dependent on number
for(int number = 29; number < 1000; number++)
because you have two nested for loops which both of them use the same variable as counter
for(int number = 29; number < 1000; number++) {
for(number = 29;number < 930;number++) {
//loops through all numbers whose sum of digits is 11
for(int number = 29; number < 1000; number++) {
//checks the values of the 100,10,and 1 position
int hPlace = number / 100;
**number** = number - (hPlace * 100); // PROBLEM!!!
int tPlace = number / 10;
**number** = number - (tPlace * 10); // PROBLEM!!!
int oPlace = number;
//sum of digits
int i = hPlace + tPlace + oPlace;
//prints if sum of digits is 11
int count = 0;
if (i == 11) {
count++;
System.out.print(i + " ");
}
//new line after every 10 numbers -- just for formatting
if (count % 10 == 0) {
System.out.println("");
}
}
if(count>500){break;} to halt it after the loop counter reaches 500....still nothing
This won't work because you're redeclaring count with an initial value of 0 everytime. So the if will always return false.
Also, these following lines:
int hPlace = number / 100; number = number - (hPlace * 100);
int tPlace = number / 10; number = number - (tPlace * 10);
Modify number, which is your loop variable. Your loop will not perform correctly if you modify the loop variable in unexpected ways. Instead, copy the value over to another variable.
Don't change the value of you loop control variable inside the loop, or dangerous things may result. Instead, copy the value into a new variable and use that in the loop.
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class SumDigits
{
public static void main(String args[])throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a Number:");
String string=br.readLine();
System.out.println("length of Number:"+string.length());
int sum=0;
int number=0;
for(int i=0;i<=string.length()-1;++i)
{
char character=string.charAt(i);
number=Character.getNumericValue(character);
sum=sum+number;
}//for
System.out.println("Sum of digits of Entered Number:"+sum);
}//main()
}//class