I'm trying to print out the numbers that are below a specific number entered as a command line argument (e.g 430) that contain specific digits (e.g 2 and 3).
So that my program prints only numbers containing 2 and 3 and are below 430, so the answer would be : 2,3,23,32, etc.
I've written a piece of code but for some reason I can't get it to work.
Any help is appreciated !
Here's my code:
public static void main(String[] args) {
int input = Integer.parseInt(args[0]);
for(int i=0; i<input; i++) {
String test= Integer.toString(i);
for(int j=0; j<test.length(); j++) {
if((test.charAt(j) != '2') || (test.charAt(j)!='3')) {
}
else {
System.out.println("The digit is " + i);
}
}
}
}
You'll never reach the else block.
if((test.charAt(j) != '0')
|| (test.charAt(j)!='1')) {
}
Should be:
if((test.charAt(j) != '0')
&& (test.charAt(j)!='1')) {
}
Here is working code. In your code, why are you checking for 0 and 1 instead of 2 and 3.
public static void main(String[] args) {
int input = Integer.parseInt(args[0]);
int two = 0, three = 0;
for (int i = 0; i < input; i++) {
String test = Integer.toString(i);
if (i < 10 && (test.equals("2") || test.equals("3"))) {
System.out.println("The digit is " + i);
} else {
for (int j = 0; j < test.length(); j++) {
if (test.charAt(j) == '2') {
two++;
} else if ((test.charAt(j) == '3')) {
three++;
}
}
if (two >= 1 && three >= 1) {
System.out.println("The digit is " + i);
}
two = 0;
three = 0;
}
}
}
Related
I have the following code that finds the prime factors from 1 to the user input. The problem is that the output is in one very long line, I want every 15 numbers to output then go to the next line. How would I do that?
Here is my code:
public static void main (String args[])
{
System.out.println("\nLab1la\n");
Scanner input = new Scanner(System.in);
System.out.println("Enter the primes upperbond ==>> ");
final int MAX = input.nextInt();
input.nextLine();
boolean primes[];
primes = new boolean[MAX];
ArrayList<Integer>PrimeFactor = new ArrayList<Integer>();
for (int i = 2; i < MAX + 1 ; i++)
{
PrimeFactor.add(i);
}
System.out.println("COMPUTING RIME NUMBERS");
System.out.println();
System.out.println("PRIMES BETWEEN 1 AND " + MAX);
CompositeNumbers(PrimeFactor);
for (int value : PrimeFactor)
{
System.out.print(value);
System.out.print(" ");
}
}
public static void CompositeNumbers(ArrayList<Integer> PrimeFactor)
{
for (int i = 0; i < PrimeFactor.size(); i++)
{
if (!isPrime(PrimeFactor.get(i)))
{
PrimeFactor.remove(i);
i--;
}
}
}
public static boolean isPrime(int n)
{
if(n==1)
{
return true;
}
for (int i = 2; i < n +1/2; i++)
{
if (n%i == 0)
{
return false;
}
}
return true;
}
}
You could do something like this:
for (int i = 0; i < PrimeFactor.size(); i++)
{
if (i > 0 && i % 15 == 0) System.out.println();
System.out.print(PrimeFactor.get(i));
System.out.print(" ");
}
You could just have a counter and take a mod of this counter value for 15 and print it in the next line, like below. Like #soong described
int counter = 0;
for (int value : PrimeFactor)
{
if(counter % 15 == 0){
System.out.println();
}
System.out.print(value);
System.out.print(" ");
counter++;
}
I'm in a beginners java class and I have a quick question about the output statement on my array problem for week 5. So basically I have the core of the program down, but I'm supposed to output the result in lines of ten. I for some reason can not get it to work even with looking at similar posts on here. I'm a beginner and am pretty slow at putting 2 and 2 together when it comes to programming. Once I see it I have that ah-ha! moment and that's how this whole class has gone. I know I have to use the modulus, but in my trial and error I lost my way and have probably done more damage than good. Help would be appreciated.
Here is what I have and as you can tell I was trying something without modulus:
import java.util.*;
public class ArrayLoop
{
public static void main(String args[])
{
double alpha[] = new double[50];
*//Initialize the first 25 elements of the array (int i=0; i<25; i++)//*
for(int i = 0; i < 25; i++)
{
alpha[i]= i * i;
}
*//Initialize the last 25 elements of the array (i=25; i<50; i++)//*
for(int i = 25; i < 50; i++)
{
alpha[i]= 3 * i;
}
*//Print the element of the array*
System.out.println ( "The values are: " );
for (int i = 0; i < 50; i++)
System.out.println ( alpha[i] );
}
*//Print method to display the element of the array*
void print(double m_array[])
{
for(int i = 1; i < m_array.length; i++)
{
if(i % 10 == 0){;
System.out.println();
}else{
System.out.print(" ");
}
}
if (m_array.length % 10 != 0) {
System.out.println();
}
}
}
Um .. this isn't eloquent in the least but I tried to make the fewest changes to your existing code sample.
public class ArrayLoop {
public static void main(String args[]) {
double alpha[] = new double[50];
for (int i = 0; i < 25; i++) {
alpha[i] = i * i;
}
for (int i = 25; i < 50; i++) {
alpha[i] = 3 * i;
}
System.out.println("The values are: ");
for (int i = 0; i < 50; i++) {
System.out.print(alpha[i] + " ");
}
System.out.println();
System.out.println();
for (int i = 1; i < alpha.length; i++) {
if (i != 1 && i % 10 == 0) {
System.out.print(alpha[i - 1] + " ");
System.out.println();
} else {
System.out.print(alpha[i - 1] + " ");
}
}
System.out.print(alpha[49]);
}
}
Edit: A better condition would be ...
for (int i = 0; i < alpha.length; i++) {
if (i > 0 && i % 10 == 9) {
System.out.print(alpha[i] + " ");
System.out.println();
} else {
System.out.print(alpha[i] + " ");
}
}
You have to print the number first then decide whether to print space or newline by checking the modulus:
int arr[] = new int[50];
// Initialize array here
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
if (i > 0 && (i + 1) % 10 == 0) {
System.out.println();
} else {
System.out.print(" ");
}
}
You have a couple of % 10 snippets in your code so I'm not entirely certain how that's "trying something without modulus" :-)
Having said that, modulus is exactly what you need, as per the following psuedo-code:
count = 0
for each item in list:
if count > 0 and (count % 10) == 0:
print end of line
print item
print end of line
In Java, you would use something like:
public class Test {
static public void main(String args[]) {
for (int i = 0; i < 24; i++) {
if ((i > 0) &&((i % 10) == 0)) {
System.out.println();
}
System.out.print ("" + i * 3 + " ");
}
System.out.println();
}
}
In other words, immediately before you print an item, check to see if it should be on the next line and, if so, output a newline before printing it.
Note that arrays in Java are zero based, so you need to start with an index of zero rather than one in your loops.
Now that's pretty close to what you have so you're on the right track but, for the life of me, I cannot see in your print() method where you actually print the item! That should be number one on your list of things to look into :-)
I urge you to try and work it out from the above text and samples but, if you're still having troubles after more than half an hour or so, the below code shows how I'd do it.
public class Test {
static void print (double m_array[]) {
for (int i = 0; i < m_array.length; i++) {
if ((i > 0) && ((i % 10) == 0))
System.out.println();
System.out.print (m_array[i] + " ");
}
System.out.println();
}
static public void main(String args[]) {
double[] x = new double[15];
for (int i = 0; i < x.length; i++)
x[i] = i * 3;
print (x);
}
}
I have a code that must print only vowels from my strings in the array list but I'm not sure if I'm doing it right in my method. How do I resolve this? Its only printing out 5 of them because I'm not sure how to directly get each specific vowels. Please find the below code that I have tried.
import java.util.*;
public class vowels {
public static void main(String[] args) {
ArrayList<String> vowels = new ArrayList<String>();
vowels.add("mitsubishi");
vowels.add("subaru");
vowels.add("nissan");
vowels.add("honda");
vowels.add("toyota");
averageVowels(vowels);
}
public static void averageVowels(ArrayList<String> vowels) {
System.out.println(vowels);
int number = 0;
for (int i = 0; i < vowels.size(); i++)
{
if (vowels.get(i).contains("a") || vowels.get(i).contains("e") || vowels.get(i).contains("i") ||vowels.get(i).contains("o") || vowels.get(i).contains("u"))
{
number++;
}
}
System.out.println("a count: " +number);
System.out.println("e count: " +number);
System.out.println("i count: " +number);
System.out.println("o count: " +number);
System.out.println("u count: " +number);
}
}
You can do without any loops, quite easily so
public static void averageVowels(ArrayList<String> vowels) {
System.out.println(vowels);
String arrayToString = vowels.toString();
int length = arrayToString.length();
System.out.println("a count: " + (length - arrayToString.replace("a", "").length()));
System.out.println("e count: " + (length - arrayToString.replace("e", "").length()));
System.out.println("i count: " + (length - arrayToString.replace("i", "").length()));
System.out.println("o count: " + (length - arrayToString.replace("o", "").length()));
System.out.println("u count: " + (length - arrayToString.replace("u", "").length()));
}
It prints
[mitsubishi, subaru, nissan, honda, toyota]
a count: 4
e count: 0
i count: 4
o count: 3
u count: 3
You want to count five types of things, so you need five variables:
int aCount = 0;
int eCount = 0;
int iCount = 0;
int oCount = 0;
int uCount = 0;
There are many different ways you could loop through each of the words, and then each of the characters in each of the words. Here's one way:
for (int i = 0; i < vowels.size(); i++) {
String lowerCaseWord = vowels.get(i).toLowerCase(); //get lowercase version so we don't have to check each letter twice
for (int j=0; j<lowerCaseWord.length(); j++){ //loop through each char in the string
char c = lowerCaseWord.charAt(j);
if (c == 'a') aCount++;
else if (c == 'e') eCount++;
else if (c == 'i') iCount++;
else if (c == 'o') oCount++;
else if (c == 'u') uCount++;
}
}
Make 5 different variables to count the number of the vowel. For example numbera, number e etc. Then you will need 5 if statements (one for each vowel) each of which will increase its respective count by 1.
for (int i = 0; i < vowels.size(); i++)
for (int j = 0; j<vowels.get(j).length(); j++) {
if (vowels.get(i).charAt('a'))
{
numbera++;
}
if (vowels.get(i).charAt('e'))
{
numbere++;
}
if (vowels.get(i).charAt('i'))
{
numberi++;
}
if (vowels.get(i).charAt('o'))
{
numbero++;
}
if (vowels.get(i).charAt('u'))
{
numberu++;
}}
This
if (vowels.get(i).contains("a") || vowels.get(i).contains("e") || vowels.get(i).contains("i") ||vowels.get(i).contains("o") || vowels.get(i).contains("u"))
only checks if the string contains a, e, i, o, or u. If it found one of these, it won't bother to check the rest of the string. And since you are using ||, in your if statement, it will not evaluate the next conditions if the current condition is already true, so it will proceed to increment number.
If you want to find the number of each vowel, One way is to loop through the string by turning it into a char array and check if a character is a vowel. Then you should create a counter for each vowel and a separated if/switch statement for each. For example with an if statement.
int aCount = 0;
int eCount = 0;
int iCount = 0;
int oCount = 0;
int uCount = 0;
for (int i = 0; i < vowels.size(); i++) {
for (char c : vowels.get(i).toCharArray()) {
if (c == 'a') {
aCount++;
} else if (c == 'e') {
eCount++;
} else (c == 'i') {
iCount++;
} else if (c == 'o') {
oCount++;
} else if (c == 'u') {
uCount++;
} else {
continue;
}
}
}
The following implementation will be efficient. Maintaining a single char array of size 256 would be good enough, which works not only for vowels but for any ASCII character.
import java.util.*;
public class Vowels {
public static void main(String[] args) {
ArrayList<String> vowels = new ArrayList<String>();
vowels.add("mitsubishi");
vowels.add("subaru");
vowels.add("nissan");
vowels.add("honda");
vowels.add("toyota");
averageVowels(vowels);
}
public static void averageVowels(ArrayList<String> vowels) {
System.out.println(vowels);
int[] chars = new int[256];
int number = 0;
for (int i = 0; i < vowels.size(); i++)
{
for (char c : vowels.get(i).toCharArray()) {
chars[c]++;
}
}
System.out.println("a count: " +chars['a']);
System.out.println("e count: " +chars['e']);
System.out.println("i count: " +chars['i']);
System.out.println("o count: " +chars['o']);
System.out.println("u count: " +chars['u']);
}
}
I need to find the last digit in a array and see if it is equal to zero. Here is the code I'm using;
import java.util.Scanner;
public class NrOccurrence
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter the integers between 1 and 100: ");
int[] numbers = new int[100], times = new int[100];
boolean zero = false;
while (zero == false)
{
for (int a = 0; a <= numbers.length; a++)
{
numbers[a] = scan.nextInt();
times[a]++;
if (numbers.equals(0))
{
zero = true;
}
}
}
for (int b = 0; b <= numbers.length; b++)
{
System.out.println(numbers[b] + " occurs " + times[b] + " times");
}
scan.close();
}
}
Create a method like this:
private boolean isLastItemZero(int[] numbers)
{
boolean isLastItemZero = false;
if ((numbers != null) && (numbers.length > 0))
{
isLastItemZero = numbers[numbers.length - 1] == 0;
}
return isLastItemZero;
}
And call it once you're done reading in all of the numbers from the user.
First of all for (int a = 0; a <= numbers.length; a++) will give youIndexOutOfBoundsException .Java uses 0 bases indexing which means that an array of size n has indices up to and including n-1. Change it tofor (int a = 0; a < numbers.length; a++) . Same thing here for (int b = 0; b <= numbers.length; b++)
Second i am not sure what you are trying to check here :
if (numbers.equals(0))
{
zero = true;
}
but you could simply do :
if(numbers[i] == 0);
Now if you wanna check if the last element in the array is 0you can simply do:
if(numbers[numbers.length - 1] == 0)
//do something
By definition, if the remainder of a number divided by 10 is 0, then the last digit must be 0. So you just need;
if(numbers[i] % 10 == 0) { zero = true; }
Hope this helps.
I am working on printing a quasi-empty square that looks like the example below (10 asterisks across and 10 down for the 2 columns):
**********
* *
* *
* *
* *
* *
* *
* *
* *
**********
My code cannot dynamically generate squares as specified by the user's input for the number of rows and columns (it is working for 10 rows and 10 columns, but as soon as I change the number to 20, the number of the asterisks does not change. The following is my code:
String STAR = "*";
String star1 = "**********";
int MAX = 10;
for (int row = 0; row <= MAX; row += 1 ) {
for (int col = 0; col <= MAX ; col += 10) {
if (row == 0 && col == 0)
System.out.println(star1);
if (row >= 1 && row <= 4)
System.out.println(STAR + " " + STAR);
if (row == 10 && col == 10)
System.out.println(star1);
}
}
Any help/advice is welcomed regarding the dynamism of the code.
String star = "*";
String space = " ";
int MAX = xxx;
for (int row = 0; row < MAX; row++) {
for (int col = 0; col < MAX; col++) {
if (row == 0 || row == MAX - 1) {
System.out.println(star);
} else if (col == 0 || col == MAX - 1) {
System.out.println(star);
} else {
System.out.println(space);
}
}
}
Look at your nested loop:
for (int col = 0; col <= MAX ; col += 10) {
So when col is 10, you're really only just iterating once... you might as well not have the nested loop at all.
Additionally, both star1 and the string literal with spaces have a fixed number of characters in them, clearly related to the number of columns.
I'm assuming this is homework, so I won't give any more hints than that to start with, but hopefully that'll get you thinking along the right lines...
You should change the 3 occurrences of 10 in your two for loops by the MAX variable, so when the user define another size, your for loop will take his input instead of the 10 value.
Also take a look at your last if statement there where it says if (row == 10 && col == 10) and think about it for a second. Once you have hit 10 rows and 10 columns, you are just going to print your final horizontal line of star1 regardless of what MAX is set too.
Like mentioned above, the nested for loop is unnecessary and can be inefficient if you plan to create larger rectangles in the future (not saying you're going to have to but try to stay away from nested for loops if you can). Instead, just print star1 before your loop begins and after it exits. The body of the loop should be simple enough. Hope this helps.
class Square
{
public static void main(String[] args)
{
String tenStars="**********";
String oneStar="*";
int count=0;
System.out.println(tenStars);
count++;
while(count<=8)
{
System.out.println(oneStar+" "+oneStar);
count++;
}
System.out.print(tenStars);
}
}
this should work
public static void hallowSquare(int side)
{
int rowPos, size = side;
while (side > 0)
{
rowPos = size;
while (rowPos > 0)
{
if (size == side || side == 1 || rowPos == 1 || rowPos == size)
System.out.print("*");
else
System.out.print(" ");
rowPos--;
}
System.out.println();
side--;
}
}
you can use something like this with one user input ... this is working
public static void drawSquare(int size)
{
for(int i=1; i<size ;i++)
System.out.print("*");
System.out.println("");
for(int i=0; i<50 ;i++)
{
System.out.print("*");
for(int j =0; j<size-3; j++)
System.out.print(" ");
System.out.println("*");
}
for(int i=1; i<size ;i++)
System.out.print("*");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
drawSquare(50);
}
you should just create a class in put this inside your class and run it ... I hope this will help you ....
class Star8
{
public static void main(String[] args)
{
for(int i=1;i<=5;i++)
{
for(int j=1;j<=5;j++)
{
if(i==2||i==3||i==4 )
{
System.out.print("* *");
break;
}
else
{
System.out.print("*");
}
}
System.out.println();
}
}
}
Hope this helps, simplify your thinking mate. Think about the axis x and y and work by that logic. Make a nested loop on ur for loop that passes lines, in each case loop the number of
the size of square and print a space, after the nested loop print the "*".
> for (int b=0;b<ans*2-3;b++)
This nested loop has the max value of b because:
remember that while ur printing, each "*" is distanced from the other by a space, and remember u are only counting space between the first and last column. Meaning all space
between x=0 and x=squaresize, therefore max b should be the space between these 2 coords.
which are: squaresize * 2 /the 2 is for the added spaces/ -3/* -3 because u leave out the first coord(x=0),last coord(x=squaresize), AND 1 space added from the former loop.
import java.util.Scanner;
public class AsteriksSquare {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input= new Scanner(System.in);
int ans;
System.out.print("Enter the size of the side of the square: ");
ans=input.nextInt();
String ast="*";
if (ans>0 && ans<21){
for(int i=0;i<=ans-1;i++){
System.out.print("* ");
}
System.out.println("");
for(int i=1;i<=ans-2;i++){
System.out.print("*");
for (int b=0;b<ans*2-3;b++){
System.out.print(" ");
}
System.out.println("*");
}
for(int i=1;i<=ans;i++){
System.out.print("* ");
}
}
}
}
class square1
{
public static void main(String[] args)
{
String star = "*";
String space = " ";
int MAX = 5;
for (int row = 0; row < MAX; row++)
{
for (int col = 0; col < MAX; col++)
{
if (row == 0 || row == MAX - 1)
{
System.out.print(star);
} else if (col == 0 || col == MAX - 1)
{
System.out.print(star);
} else {
System.out.print(space);
}
}
System.out.println();
}
}
}
This code should do the trick.
package javaPackage;
public class Square {
public static void main(String [] args)
{
for (int i=0;i<=10;i++)
{
for (int j=0;j<=10;j++)
{
if(i==0||i==10){
System.out.print("x");
}
else if(j==0||j==10){
System.out.print("x");
}
else{
System.out.print(" ");
}
}
System.out.println();
}
}
}
If the interpreter sees that you're on the first and last line(i=0 and i=10), it will fill the row with x. Else, it will only print a x at the beginning and the end of the row.
you can use below two methods.
1) One with minimal line of code.
for (int i = 0; i <= 9; i++) {
if (i == 0 || i == 9) {
System.out.println("* * * *");
} else {
System.out.println("* *");
}
}
OR
2) With the help of two for loops
for (int i = 0; i <= 9; i++) {
for (int j = 0; j <= 9; j++) {
if (i == 0 || i == 9) {
System.out.print("*");
} else {
if (j == 0 || j == 9) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
}
System.out.println();
}
Thanks,
Stuti
Here's another solution, a more versatile one. It lets you create a hollow rectangle of height "h" and width "w"
private static void hallowSquare(int h, int w)
{
for(int i=1; i<=h; i++)
{
for(int j=1; j<=w; j++)
{
if (j==1|| j==w || i==1 || i==h )
System.out.print("X");
else
System.out.print(" ");
}
System.out.println();
}
}
import java.util.Scanner;
class Star
{
public static void main(String...args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the row : ");
int row=sc.nextInt();
System.out.print("Enter the column : ");
int column=sc.nextInt();
for(int i=1;i<=column;i++)
{
System.out.print("*");
}
for(int i=row-2;i>=1;i--)
{
System.out.println();
System.out.print("*");
for(int k=1;k<=column-2;k++)
{
if(i<1)
{
break;
}
System.out.print(" ");
}
System.out.print("*");
}
System.out.println();
for(int i=1;i<=column;i++)
{
System.out.print("*");
}
}
}
I am hopeful the code below can help, used very simple coding and have the required result.
a=eval(input('Provide the height of the box: '))
b=eval(input('Provide the width of the box: '))
d=a-2
r=b-2
if a >= 1:
print('*'*b)
if a > 1:
for i in range(d):
print('*',end='')
for i in range(r):
print(' ',end='')
print('*')
print('*'*b,end='')
The result is: