The goal of my code: To be able to write a program where I can enter in any number int as a command-line argument and displays how many digits in the integer number are 7s.
My problem is that I don't understand why my code only runs through the for-loop once. I inserted the system.out.println(sevens); to see how many times this loop works when I compile with a random number like 456789.
I could only think of a for-loop to use for this one and fixed some simple mistakes in the beginning. I also checked my brackets
public class TestingSevens {
public static void main(String[] args) {
int sevens = Integer.parseInt(args[0]);
int count = 0;
for (int i = 0; i < args.length; i++) {
if (sevens%10 == 7) {
count += 1;
}
sevens = sevens/10;
System.out.println(sevens);
}
System.out.println(count);
}
}
The result of inputting a number like 456789 is "45678" for the first print and the second print is "0." I know the number for some reason only runs through the loop once since it cuts off the last number before jumping out of the loop to print the count...any advice?
I presume you want to iterate over each digit of sevens. Since sevens initialized from args[0], the loop limit should match and look at args[0].length() rather than args.length.
for (int i = 0; i < args[0].length(); i++)
An alternate way to write the loop is to iterate until sevens reaches 0. That lines up better with the loop body; both use the same variable.
while (sevens > 0) {
if (sevens%10 == 7) {
count += 1;
}
sevens /= 10;
System.out.println(sevens);
}
Your code has logic errors, so to check if the iterated number is number 7 you need to turn the number into a string and check if the character is the desired character using: numberString.charAt(index)
Below is the corrected code:
public static void main(String[] args) {
int sevens = Integer.parseInt(args[0]);
String numberString = String.valueOf(sevens);
int count = 0;
for (int i = 0; i < numberString.length(); i++) {
char c = numberString.charAt(i);
if (c == '7') {
count += 1;
}
System.out.println("Input number: " + sevens);
}
System.out.println("Count of 7 numbers: " + count);
}
Related
I want to...
create an asterisk triangle, using Java, that matches the length of whatever number (Between 1-50) the user enters.
Details
The first line would always start with an asterisk.
The next line would increment by one asterisk until it matches the
user's input.
The following lines would then decrement until it is back to one
asterisk.
For instance, if the user was to enter 3, then the output would have one asterisk on the first line, two asterisks on the second line, three asterisks on the third line, and then revert back to two asterisks on the following line before ending with an asterisk on the last line.
What I've tried so far
I am required to use nested for loops. So far, I tried to test it out using this practice example I made below. I was only able to create on output of the numbers. I also have some concepts of outputting asterisk triangles. How can I apply the concept of this code to follow along the user's input number?
import java.util.Scanner;
public class Program
{
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int count, index = 0, value, number;
System.out.println("This program creates a pattern of numbers " );
System.out.println("Based on a number you enter." );
System.out.println("Please enter a positive integer. " );
count = keyboard.nextInt();
value = count;
for (index = 1; index <= count; index++)
{
for (number = value; number >= 1; number--)
{
System.out.println(number);
}
value--;
System.out.println();
}
}
}
Here's how i would proceed
write a method printAsterisks that takes an int N as parameter and writes a line of N asterisks. You wil need a for loop to do so.
call printAsterisks in a for loop that counts from 1 to COUNT
call printAsterisks in a second loop that counts down from COUNT-1 to 1
That should do the trick.
Also, as a side note, you should close your scanner. The easy way to do so is enclose ot in a try-with-resource like so :
try (Scanner keyboard = new Scanner(System.in);) {
// your code here
}
Let us know the version of the program taht works (or the question you still have) :)
HTH
Here is what you want:
public class Asterisk {
private static final String ASTERISK = "*";
private static final String SPACE = "";
private static int LENGTH;
public static void main(String[] args) {
try{
readLength();
for (int i=1; i<=LENGTH; i++) {
if (i == LENGTH) {
for (int j=LENGTH; j>=1; j--) {
drawLine(j);
}
break;
}
drawLine(i);
}
}catch (Exception e) {
System.out.println("You must enter a number between 1 and 50.");
}
}
static void readLength(){
System.out.println("Enter asterisk's length (1-50)");
LENGTH = Integer.parseInt(System.console().readLine());
if (LENGTH<=0 || LENGTH>50)
throw new NumberFormatException();
}
static void drawLine(int asterisks){
StringBuilder line = new StringBuilder();
int spacesLeft = getLeftSpaceCount(asterisks);
int spacesRight = getRightSpaceCount(asterisks);
for (int i=0; i<spacesLeft; i++) {
line.append(SPACE);
}
for (int i=0; i<asterisks; i++) {
line.append(ASTERISK);
}
for (int i=0; i<spacesRight; i++) {
line.append(SPACE);
}
System.out.println(line.toString()+"\n");
}
static int getLeftSpaceCount(int asterisks){
int spaces = LENGTH - asterisks;
int mod = spaces%2;
return spaces/2 + mod;
}
static int getRightSpaceCount(int asterisks){
int spaces = LENGTH - asterisks;
return spaces/2;
}
}
I am required to use nested for loops
Yes, the main logic lies there...
for (int i=1; i<=LENGTH; i++) {
if (i == LENGTH) {
for (int j=LENGTH; j>=1; j--) {
drawLine(j);
}
break;
}
drawLine(i);
}
The triangle using 5 as input.
*
**
***
****
*****
****
***
**
*
Tip:
There is an easier way to get input from the user usingSystem.console().readLine().
In regards to the printing part, I wanted to clean up the answers a little:
int input = 3; //just an example, you can hook in user input I'm sure!
for (int i = 1; i < (input * 2); i++) {
int amount = i > input ? i / 2 : i;
for (int a = 0; a < amount; a++)
System.out.print("*");
}
System.out.println();
}
For our loop conditions, a little explanation:
i < (input * 2): since i starts at 1 we can consider a few cases. If we have an input of 1 we need 1 row. input 2, 3 rows. 4: 5 rows. In short the relation of length to row count is row count = (length * 2) - 1, so I additionally offset by 1 by starting at 1 instead of 0.
i > input ? i / 2 : i: this is called a ternary statement, it's basically an if statement where you can get the value in the form boolean/if ? value_if_true : value_if_false. So if the row count is bigger than your requested length (more than halfway), the length gets divided by 2.
Additionally everything in that loop could be one line:
System.out.println(new String(new char[i > input ? i / 2 : i]).replace('\0', '*'));
And yeah, technically with a IntStream we could make this whole thing a one-line, though at that point I would be breaking out newlines for clarity
Keep in mind, I wouldn't call this the "beginner's solution", but hopefully it can intrigue you into learning about some other helpful little things about programming, for instance why it was I replaced \0 in my one-line example.
I've recently taken up a computer organization course in where we learn binary hex etc, I took it upon myself to attempt to create a program that will count from 0 up to an input number, however the counting is done in binary. I've run into some trouble and confused myself beyond belief, some clarification and assistance would be greatly appreciated. Specifically speaking, how can I efficiently and effectively replace the values of a string containing the previous binary number, with 0's and 1's using some sort of for-loop. I'm aware that there is some method for directly converting a string to binary, however; I wanted to do this more complicated method for practice.
package counting;
import java.util.Scanner;
public class counting
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Hello, this is a number counter, please enter the integer you would like to count to");
int number = input.nextInt();
String start = "0000000000";
// 000~etc is used as the start simply because i'm not sure how to calculate how many digit places
//the number input by the user will have
StringBuilder cont = new StringBuilder(start);
System.out.println(start);
/*What i intend to do is have the binary loop counter continue until it reaches
* the number input by the user, afterwards, working in a right to left manner, start counting from
* 0 up to the number given by the user, starting with 0. then using another loop, still using
* the right to left manner, if there is a 0, it should be replaced with a 1, and if there is a
* 1, it should be replaced with a 0, and the character before it should be replaced with a 1, if there
* is no room, continue to the left until there is a space available for a 1 and then reset all values
* after the 1 back to zero, and resume counting. the way i see it is requires a for loop to be used
* as the current position of a cursor used to determine what changes must be made
*/
for(int i = 0; i < number; i++)
{
int l = start.length();
for(int n = 0; n <= number; n++)
{
for(int w = 1; w <= l; w++)
{
if (cont.charAt(l-w) == '0')
{
cont.setCharAt((cont.length()-w), '1');
System.out.println(cont);
}
else if (cont.charAt(l-w) == '1')
{
cont.setCharAt((cont.length()-w), '0');
cont.setCharAt((cont.length()-(w+1)), '1');
System.out.println(cont);
}
}
}
System.out.println(cont);
}
}
}
Here is a little loop that will do what you are looking for. You just have to remember powers of 2 to count in binary.
public static char flip(char c){
if(c == '0')
return '1';
else
return '0';
}
public static void main(String[] args) {
String start = "0000000000";
StringBuilder cont = new StringBuilder(start);
int number = (int)Math.pow(2,10);
for(int i = 0; i < number; i++)
{
if(i != 0){
int val = (int)Math.floor(i/2);
for(int j = 0; j <= val; j++){
// Flip any bit that when modded by 2^j == 0
if(i % Math.pow(2,j) == 0){
cont.setCharAt((cont.length() - (j + 1)), flip(cont.charAt(cont.length() - (j + 1))));
}
}
}
System.out.println(cont);
}
}
I'm supposed to create and initialize a 100-element array, then make the 7th element the number "7", and finally print the array, starting a new line every 20 elements. I've been trying to figure this out for a long time and I can't.
My code right now is:
public class Array {
public static void main(String args[]) {
int [] array = new int[100];
for (int a = 0; a < array.length; a++) {
if (array[a] == 6) {
array[a]=7;
array[a] = a + 1;
}
printArray(array);
}
}
public static void printArray(int[] array){
for (int a=0; a < array.length; a++) {
System.out.print(" " + array[a]);
if ((a - 1) % 20 == 0) {
System.out.println("");
}
}
}
}
When I run this my output is a lot of zeros, far more than 100. They are separated every 20 characters as intended, but the seventh element is not 7. I think it has to do with the association between int "a" and my array, but I can't figure it out. I know the solution must be simple but I just cannot see it. Thank you all!
Proper indentation of your code, in particular the main method, reveals what is going on. You are calling printArray from within the for loop, so you are printing the array contents 100 times.
for (int a = 0; a < array.length; a++) {
if (array[a] == 6) {
array[a]=7;
array[a] = a + 1;
}
printArray(array);
}
Move the call to printArray after the } ending brace for the for loop.
Now you'll get 100 0s.
Also, I think you meant to have array[a] = a + 1; executed if the index was not 6, e.g.
if (array[a] == 6) {
array[a] = 7;
} else {
array[a] = a + 1;
}
Additionally, you will want to print a newline after 20 numbers, e.g. after indexes 19, 39, etc., so add 1 to a before calculating the remainder, instead of subtracting 1, so that 19 + 1 = 20, whose remainder is 0.
There are many things wrong. However, to answer your question, you are printing the array 100 times since printArray is inside your first loop.
You misplaced an end parenthesis in your main method. The properly formatted method looks like this:
public static void main(String args[]) {
int [] array = new int[100];
for (int a = 0; a < array.length; a++) {
if (array[a] == 6) {
array[a]=7;
}
array[a] = a + 1;
}
printArray(array);
}
First of all your code is organized very badly so it's very easy for u to miss what went where. You have 2 major mistakes, first of all you called printArray()
Inside your for loop and therefore printed it 100 times.
Second, you kept checking if the value inside the array in index a is 6.
You need to check if a is 6 since it is your index like this:
if(a == 6)
array[a] = 7;
Well, I ran your code, and there are a few places that can be corrected.
As for your problem of the many things being printed, that's because you've placed your printarray() inside the for loop, so it's printing the array 100 times.
As for printing it out, i find this code to be more concise:
public static void printArray(int[] array){
int counter = 0;
for(int i = 0; i < array.length; i++){
System.out.print(array[i] + " ");
counter++;
if(counter == 20){
counter = 0;
System.out.print("\n");
}
}
}
Also, I'm not really sure why you're using a for loop to just change the 7th element. You could use this:
array[6] = 7;
I'm not really sure what you're doing in the for loop.
I hope this helped! Good luck!
So, for an assignment in my computer science class, we've got to use loops, either for or while, depending on preference. Now, the assignment IS to use said loops and a given input to draw a beauteous ASCII diamond made of '$' and '-'. Say, an input of 5 would look like:
____$
___$-$
__$-$-$
_$-$-$-$
$-$-$-$-$
_$-$-$-$
__$-$-$
___$-$
____$
The underscores are to denote spaces. Now, anytime I try using
public static void main(String[] args) {
String input=JOptionPane.showInputDialog(null, "Input a number between three and ten here: ");
double length=Double.parseDouble(input);
int i=0; int j=0;
for(i=1; i<length; i++)
{
System.out.print(" ");
for(j=1; j<=i; j++)
{
if(j<i){System.out.print("-$");
}
else if(j==i){System.out.println("");}
}
}
I come out with something like, say, for input=7:
-$
-$-$
-$-$-$
-$-$-$-$
-$-$-$-$-$
And yes, the two too few in the center is true with any input. Any help?
Since this is your homework, I'm just going to point you towards the correct answer and leave you to figure out the rest. Let's try formatting your code so you can see what's going on:
public static void main(String[] args) {
String input=JOptionPane.showInputDialog(null, "Input a number between three and ten here: ");
double length=Double.parseDouble(input);
int i=0; int j=0;
for(i=1; i<length; i++){
System.out.print(" ");
for(j=1; j<=i; j++){
if(j<i){
System.out.print("-$");
}
else if(j==i){System.out.println("");
}
}
}
Now, you've got an outer loop for i ranging from 1..length-1, and for each i you're going to print a space, then you're going to count from 1 to 1 and print "-$" that many times. Then, you're going to print a newline and repeat the outer loop, incrementing i
So, the first time through the outer loop, you print one space, followed by one "-$", followed by a newline. Then on the second time through the outer loop, you print one space, followed by "-$" twice, followed by a newline. And so forth, until i=length, and then you stop.
You want to print a few more spaces before you print dollar signs - a loop here will probably be useful.
try to go trough this code and see how it works... it might be useful for your homework
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("input a number");
int number = input.nextInt();
input.close();
boolean add = true;
int counter = 0;
do {
if (add) {
counter++;
print(' ', number - counter);
print('$', counter);
if (counter == number)
add = false;
System.out.println();
} else {
counter--;
if (counter == 0)
break;
print(' ', number - counter);
print('$', counter);
System.out.println();
}
} while (true);
}
private static void print(char c, int times) {
if (c == '$')
times = (times * 2) - 1;
for (int i = 0; i < times; i++)
System.out.print(c);
}
if you edit the print method you will get your desired result
private static void print(char c, int times) {
if (c == '$')
times = (times * 2) - 1;
for (int i = 0; i < times; i++)
if (i % 2 == 1 && c == '$')
System.out.print('-');
else
System.out.print(c);
}
I'm trying to find prime numbers with a specific condition in Java.
The challenge is to show all the prime numbers (under 100.000) which contain a '3' four times.
I already have a code which shows all the prime numbers under 100.000, but I can't seem to figure out how to count the ones that contain the number '3' four times.
I can however count all the prime numbers.
Can someone help me with this?
Here's the code I have, where am I going to put the numbers into strings?
package Proeftentamen;
import java.util.regex.*;
/**
*
* #author Stefan
*/
public class Vraag_6 {
/// priemgetallen waar 4x een 3 in voor komt???? wtf...
public static void main(String[] args) {
boolean[] lijst = new boolean[1000000]; // hoeveelheid getallen
vularray(lijst);
lijst = zeef(lijst);
drukaf(lijst);
}
public static void vularray(boolean[] lijst) {
for (int i = 2; i < lijst.length; i++) {
lijst[i] = true;
}
}
public static boolean[] zeef(boolean[] lijst) {
for (int i = 2; i < lijst.length / 2; i++) {
if (lijst[i]) {
for (int j = 2 * i; j < lijst.length; j += i) {
lijst[j] = false;
}
}
}
return lijst;
}
public static void drukaf(boolean[] lijst) {
int count = 0;
for (int i = 2; i < lijst.length; i++) {
if (lijst[i] == true) {
System.out.println(i + " " + lijst[i]);
count++;
}
}
System.out.println("Aantal priemgetallen: " + count);
}
}
This question really sounds like a homework, so you should write down what you have come up with and what you tried so far.
There are a lot of ways to count numbers. Just to give you a clue, you can use the reminder operation (in Java - %):
56 % 10 = 6
25 % 5 = 0
So, when you divide by 10 and use a reminder operation you can get the last digit of your number. Now use a loop and counter and you'll be fine.
Another option (very ugly, so don't really use it :) ) - to turn your number into a String and iterate (loop) over its characters.
Hope this helps and good luck!
This code generate 50 permutation of numbers that has four '3' in it's digits
so check each number that is prime or not
public void generateNumbers() {
StringBuilder s = new StringBuilder();
s.append("3333");
for (int i = 0; i < 5; i++) {
for (int j = 0; j <= 9; j++) {
if (j%3==0) continue;
s.insert(i,String.valueOf(j));
int number=Integer.parseInt(s.toString());
System.out.println(number);
s.delete(i,i+1);
}
}
}
Iterate across each prime number.
For each prime number, convert it to a string using the Integer.toString(int) static method.
With this string, iterate over every character (use a for loop and the non-static method String.charAt(int index)) and count the number of times that method returns '3'. (The character '3', not the String "3").
Unless you have some other purpose for an array of prime-number Strings, don't bother to store them anywhere outside the loop.
Please refer below code to validate all such prime numbers.
void getPrimes(int num ,int frequency,char digit) {
int count = 0;
String number=Integer.toString(num);
for (int i = 0; i < number.length(); i++) {
if (count < frequency) {
if (number.charAt(i) == digit)
count++;
}
if (count == frequency)
{
System.out.println(number);
return ;
}
}
}
Using the primes function from an exercise on the Sieve of Eratosthenes, as well as the digits and filter functions from the Standard Prelude, this Scheme expression finds the seven solutions:
(filter
(lambda (n)
(= (length
(filter
(lambda (d) (= d 3))
(digits n)))
4))
(primes 100000))
The outer filter runs over all the primes less than 100000 and applies the test of the outer lambda to each. The inner filter computes the digits of each prime number and keeps only the 3s, then the length function counts them and the equality predicate keeps only those that have 4 3s. You can run the program and see the solution at http://codepad.org/e98fow2u.
you only have at most five digits, four of which must be 3. So what can you say about the remaining digit?
It's not hard to just write out the resulting numbers by hand, and then test each one for primality. Since there are no more than 50 numbers to test, even the simplest trial division by odds will do.
But if you want to generate the numbers programmatically, just do it with 5 loops: add 10,000 to 03333 9 times; add 1,000 to 30333 9 times; add 100 to 33033 9 times; etc. In C++:
int results[50];
int n_res = 0;
int a[5] = {13333, 31333, 33133, 33313, 33331};
for( int i=0, d=10000; i<5; ++i, d/=10)
for( int j=1; j<9; ++j, a[i]+=d )
if( is_prime(a[i]) )
results[n_res++] = a[i];