I'm trying to make a program that asks a user for two numbers. I want to determine how many times a certain value appear in the sequence of numbers. For instance, if user entered 10 and 20 the number "1" would appear 9 times. What I am wondering is what condition would I have to set to see how many times the number "1" would appear.
This is what I got so far...
System.out.println("Enter a number: ");
int no1 = scan.nextInt();
System.out.println("Enter a number: ");
int no2 = scan.nextInt();
int i;
int j = 0;
for(i = no1; i <= no2; i++){
if(){ // Some condition here
j++;
}
}
System.out.println(j);
}
Any other tips and tricks on how to make my code efficient would also be greatly appreciated.
for (int i = no1; i <= no2; i++) {
if(String.valueOf(i).contains("1"))
int occurances = StringUtils.countOccurrencesOf(String.valueOf(i), "1");
j+=occurances
}
Assuming that you want to count the occurrences of a digit within a list of numbers you could e.g. use modulo:
int[] occurrences = new int[10];
for (int i = n1; i <= n2; i++) {
int currentNumber = Math.abs(i);
while (currentNumber > 0) {
occurrences[currentNumber % 10]++;
currentNumber /= 10;
}
}
or parse the string representation of the number
int[] occurrences = new int[10];
for (int i = n1; i <= n2; i++) {
String cur = String.valueOf(Math.abs(i));
for (int j = 0; j < cur.length(); j++) {
char currentChar = cur.charAt(j);
if (currentChar != '-')
occurrences[Character.getNumericValue(currentChar)]++;
}
}
occurrences will contain the counts for digits from 0 to 9;
Edit: Added handling for negative integers.
Related
How do I stop the loop if the number reaches the n? i tried the break; but the loop still doesn't stop.
Scanner in = new Scanner(System.in);
int i, j;
int n = in.nextInt();
int number = 1;
for(i = 1; i <= n; ++i) {
for(j = 1; j <= i; ++j) {
System.out.print(number);
++number;
if(number >= n){
break;
}
}
System.out.println();
}
input: 9
expected output:
1
23
456
789
or
input: 12
expected output:
1
23
456
78910
1112
Break and Labeled break should be avoided in code. So you can use loops as below:
public static void main(final String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please enter input number:");
int n = in.nextInt();
System.out.println("You have entered : " + n);
for (int i = 1, k = 1; k <= n; i++) {
for (int j = 0; j < i && k <= n; j++, k++) {
System.out.print(k);
}
System.out.println();
}
}
Printing k variable which is initialized in outer and updated in inner loop.
Putting condition to break inner and outer loop to check k with input variable
EDITED : To understand it better:
i variable is used to maintain the number of rows we need to print.
j variable is used to maintain the number to elements to print in each row.
In most of placed the value which is being print is in context with either row number or element number in row, but here print value is not in sync with it, so we are maintaining it in 2rd variable k.
Use the labeled break statement and you can break from the nested loop:
loop:
for (int i = 1; i <= n; ++i)
{
for (int j = 1; j <= i; ++j)
{
System.out.print(number);
++number;
if (number > n) //not (number >= n)
{
break loop;
}
}
System.out.println();
}
There are many ways of doing this. The most straightforward one is to use a label to break out of several loops at once:
outer: for(i = 1; i <= n; ++i) { // a label is a word followed by :
inner: for(j = 1; j <= i; ++j) { // you can declare labels without using them
System.out.print(number);
++number;
if(number >= n){
break outer; // break inner would be equivalent to what you had
}
}
System.out.println();
}
However, these break statements with labels look suspiciously similar to gotos, and gotos are frowned upon. A more teacher-friendly version would be to use a boolean flag, and check the flag in each loop:
boolean finished = false;
for(i = 1; i <= n && ! finished; ++i) {
for(j = 1; j <= i && ! finished; ++j) {
System.out.print(number);
++number;
if (number >= n) {
finished = true; // no need to break - loops condition will now be false
}
}
System.out.println();
}
Note that this introduces an extra newline, which you generally want to make sure that whatever you print next appears on a different line.
Another option is to simply complicate your initial condition, without any flags:
for(i = 1; i <= n && number < n; ++i) {
for(j = 1; j <= i; ++j) {
System.out.print(number);
++number;
}
System.out.println();
}
I would recommend, for readability purposes, version 2. Additionally, I would write it as follows:
boolean finished = false;
for(int i = 0; i < n && ! finished; ++i) {
for(j = 0; j < i && ! finished; ++j) {
System.out.print(number++);
if (number >= n) {
finished = true;
}
}
System.out.println();
}
The key differences are using 0 to n-1 counting to repeat something n times (most programmers are very accustomed to that, instead of counting from 1 to n), and defining loop variables within the for, so that trying to use them outside of their loops is an error. This helps to avoid accidental reuse of variables.
import java.util.Scanner;
public class Tester{
public static void main(String []args){
Scanner in = new Scanner(System.in);
int i, j;
int n = in.nextInt();
int number = 1;
loop:
for ( i = 1; i <= n; ++i){
for ( j = 1; j <= i; ++j){
System.out.print(number);
++number;
if (number > n)
{
break loop;
}
}
System.out.println();
}
}
}
by using a for loop with a nested one you can achieve it like this:
you have a row which is incremented by 1 on each row (line)
you have a column variable which is increasing by one on each line or row
you have a number with start to print from 1 till the inputed number for example it was entered 12.
in inner loop you need to check the column be less or equal to row and the incremented number be less the entered number.
Scanner in = new Scanner(System.in);
System.out.print("Enter a Number: ");
int n = in.nextInt();
int number = 1;
for (int row = 1; row <= n && number <= n; row++) {
for (int column = 1; column <= row && number <= n; column++) {
System.out.print((number++) + " ");
}
System.out.println();
}
So a jist of what the program needs to do is to count how many integers are greater than the average of the sum of all elements in an array. It does this as the last number it counts is the total number of integers greater than average. However, it also shows the number of times it has looped. For example, if the number of integers is supposed to be 3, it will show, 1,2,3. That's fine but the 1,2, the part is not necessary, just the 3. This is the only way I have found possible but is there a better way?
import java.util.Scanner;
public class Sparky
{
public static void main(String[] args)
{
Scanner kbd = new Scanner(System.in);
int sum =0;
int n;
do
{
System.out.print("Enter integer n, greater than 0: ");
n = kbd.nextInt();
}while(n < 1);
System.out.println();
int[] arr = new int[n];
System.out.println("Array on one line: ");
for(int i = 0; i < arr.length; i++)
{
arr[i] = (int) (Math.random() * 500) + 1;
System.out.print(arr[i] + " ");
}
int max = arr[0];
for(int i = 1; i < arr.length; i++)
{
if(arr[i] > max)
{
max = arr[i];
}
}
System.out.println();
{
double x = 0;
double y;
for(int i = 0; i < arr.length; i ++){
x = arr[i] + x;
}
y = x / arr.length;
System.out.println("Average: " + y);
System.out.println("Number of integers greater than average: ");
int count = 1;
for(int i = 0; i < arr.length; i ++)
{
if(arr[i] > y)
{
System.out.print(count + ",");
count ++;
}
}
}
}
}
Change the last section of your code from this :
for(int i = 0; i < arr.length; i ++)
{
if(arr[i] > y)
{
System.out.print(count + ",");
count ++;
}
}
To this :
for(int i = 0; i < arr.length; i ++)
{
if(arr[i] > y)
{
count ++;
}
}
System.out.print(count);
It should print the number of integers greater than average.
Xerox's answer was good, but I noticed a bug in your code. If you start count at 1, your count will be off. Also, I thought I'd show you how to use a foreach loop. So I made some updates to your code, ran it, and added comments for you. Remember, short variable names were used in the 80s because they took up disk space and slowed down processing time when they were larger. That's no longer an issue, and if your variable names are cryptic, your code is difficult to read, even when it's simple. You'll notice that your code is much easier to read with descriptive variable names and a foreach loop. I left the rest of the file for you to do if you are interested.
import java.util.Scanner;
public class Sparky {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
int n;
do {
System.out.print("Enter integer n, greater than 0: ");
n = kbd.nextInt();
} while (n < 1);
System.out.println();
int[] arr = new int[n];
System.out.println("Array on one line: ");
for (int i = 0; i < arr.length; i++) {
arr[i] = (int) (Math.random() * 500) + 1;
System.out.print(arr[i] + " ");
}
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
System.out.println();
{
double x = 0;
double average; //Better to have readable variables. "y" means nothing, "average" is clear, especially in the next section.
for (int i = 0; i < arr.length; i++) {
x = arr[i] + x;
}
average = x / arr.length;
System.out.println("Average: " + average);
int numberGreaterThanAverage = 0; //This needs to start at 0 or your count will be off. Also, name the variable what it does. Short variable names help no one.
for (int number: arr) { //This is called a foreach loop. It does the same thing as your loop, but is much each to read, also I renamed "i", short for "iterator" to "number" which is what it actually is, a number in the array.
if (number > average) {
numberGreaterThanAverage++;
}
}
System.out.println("Number of integers greater than average: " + numberGreaterThanAverage); //This needed to be moved out of the loop, and it also could be concatenated with the rest of the text to put it all on one line.
}
kbd.close(); //You need to close this or you can get a memory leak
}
}
Always consider printing statements after you are done with modifying the values, best is to print outside the loop.
In this case, Count is being printed before it is incremented, on the last iteration of the loop, it increments and quits the loop.
for(int i = 0; i < arr.length; i ++)
{
if(arr[i] > y)
{
// System.out.print(count + ","); count is being printed before it is incremented
count ++;
}
}
System.out.print(count + ","); //Should be printed **after** the loop ends.
so i'm having a little issue with my code for my class.
my code looks like this:
Scanner scnr = new Scanner(System.in);
int n = 0;
System.out.println("Please enter a number 1...9 : ");
n = scnr.nextInt();
int i = 0;
int k = 0;
int j = 0;
int l = n;
String space = " ";
for (i = 1; i <= n; i++) {
for (k = i; k < n; k++) {
System.out.print(" ");
}
for (j = i; j > 0; --j) {
System.out.print(j + "");
}
System.out.println("");
}
my output looks like
-----1
---21
-321
4321
and my expected output is supposed to look like this:
-----1
--2-1
3-2-1
(assume the '-' are spaces)
I just need spaces between the numbers, but every time I do so, I get a full on triangle. If anyone could help me out with this I would really appreciate it! Thank you!
Based on your question, I understand you wish to put spaces between the numbers that the user selects. So an example output would be:
Please enter a number 1...9 :
9
1 2 3 4 5 6 7 8 9
If this is what you want, then just do this:
Scanner scnr = new Scanner(System.in);
System.out.println("Please enter a number 1...9 : ");
int n = scnr.nextInt();
for (int i = 1; i <= n; i++){
System.out.print(i + " ");
}
It's not wrong, what you did you just missed the right places to add a space. I formatted you for loops so that the numbers are displayed in an right angle. For your information you can define the variables in the for loop for(int i .... ) this makes it easier to read. Here is the version with the spaces.
for (int i = 1; i <= n; i++) {
for (int k = i; k < n; k++) {
System.out.print(" ");
}
for (int j = i; j > 0; --j) {
System.out.print(j + " ");
}
System.out.println("");
}
You are concatenting the digit with an empty String. If you concatenate a single space then you will generally get the output you want. You will have a trailing space. This is unlikely to be an issue.
You defined a space variable you probably intended to use as a constant for this construction. It conventional to mark constants final and use an all-caps name.
final String SPACE = " ";
...
for (j = i; j > 0; --j) {
System.out.print(j + SPACE);
}
An alternative is to us a StringJoiner to compose the String and then output the String.
StringJoiner joiner = new StringJoiner(SPACE);
for (j = i; j > 0; --j) {
joiner.add(j);
}
System.out.println(joiner.toString());
Can someone please explain the thought process behind this code? I am kind of confused on how it works. This is the question that the code is addressing:
Write code (using one or more loops) to fill an array "a" with 10 different random numbers between 1 and 10.
Thank you so much for any help!
public static void main(String[] args){
//R8.8
int a[] = new int[10];
Random randomGenerator = new Random();
for (int i = 0; i < a.length; i++){
a[i] = 1 + randomGenerator.nextInt(100);
}
for (int i = 0; i < a.length; i++) {
int number = 1 + randomGenerator.nextInt(100);
int count = 0;
for (int j = 0; j < i; j++) {
if (a[j] == number) {
count += 1;
}
}
if (count > 0) i -= 1;
else a[i] = number;
}
}
}
See my comments in the code itself:
public static void main(String[] args){
//make a new array of 10 integers
int a[] = new int[10];
//declare an object which we can use to generate random numbers
//this object probably uses the system time to generate numbers that appear random
//but at the end of the day, java does it for us so
//we don't really need to know or care how it generates random numbers
Random randomGenerator = new Random();
//loop over each element in our array
for (int i = 0; i < a.length; i++){
//for each element, set that element to a random between 1 and 100 inclusive
//nextInt(x) gets a number between 0 (inclusive) and x (not inclusive)
//so to translate that to 1 to x inclusive, we need to add 1 to the result
a[i] = 1 + randomGenerator.nextInt(100);
}
//everything below here does literally nothing to solve the problem
//everything you need to fill the array with random numbers is above
for (int i = 0; i < a.length; i++) {
int number = 1 + randomGenerator.nextInt(100);
int count = 0;
for (int j = 0; j < i; j++) {
if (a[j] == number) {
count += 1;
}
}
if (count > 0) i -= 1;
else a[i] = number;
}
}
}
Please note that you should use 1 + randomGenerator.nextInt(10); to fill the array with numbers between 1 and 10, not 1 + randomGenerator.nextInt(100);.
Anyone able to steer me in the right direction. I am building a simple mark program where I get input from Scanner and insert it into my 2D array. I want to validate my input so that it isn't below 0 or above 100 but if I have the incorrect number I don't want the array to move to next position.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);//naming the scanner
String [] student = {"Mark","Jen","Gaby","John","Michael","James"};
String [] subject = {"Digital electronics","Analogue electronics","Maths","Networks","Telecommunications",
"Computer applications","Software developemnt","Workshop"};
String [] printSub = {"Digit","Analo","Maths","Netwo","Telec","Appli","Softw","Works"};
int maxRow = 6;//setting max row amount int
int maxCol = 8;//set max column amount int
int [][] mark = new int [maxRow][maxCol];//declaring the int array and setting the row & column max.
int i = 0, j = 0;//declaring i and j for use in the for loops
int maxMark = 0;//declaring for use in if statement to find highest mark
int minMark =100;//Declaring for use in if statement to find lowest mark
for(i = 0; i < maxRow; i++)
{
for(j = 0; j < maxCol; j++)
{
System.out.print("Please enter "+student[i]+" mark for "+subject[j]+" and press return :");
mark[i][j]= input.nextInt();
}
}
for(i=0; i < maxRow; i++)
{
for(j=0; j < maxCol; j++)
{
if (i == 0 && j == 0)
{
System.out.print("Student \t");
for(int sub = 0; sub < 8; sub++)
{
System.out.print(printSub [sub]+"\t");
}
System.out.println();
System.out.println();
}
if(i < maxRow && j == 0)
{
System.out.print(student[i]+"\t \t ");
}
System.out.print(mark [i][j]+"\t");
}
System.out.println();
System.out.println();
}
}
I am not looking for the answer i am looking for more of a nudge in the direction where I may be able to figure out the answer myself.
Thanks for the help in advance.
Matt
Nudge : You do not directly insert number into array, you insert it into some temporary variable, checks it and then decide if you save it or you ask again (while cycle needed)
Spoiler 1 : Here is complete solution, if you want to do it yourself, do not look there :) :
for (i = 0; i < maxRow; i++) {
for (j = 0; j < maxCol; j++) {
System.out.print("Please enter ");
int number = input.nextInt();
boolean isItOk = false;
while (isItOk == false) {
if (number < 0 || number > 100) {
System.out.println("You shall not insert a value below 0 or bigger than 100! Try it again");
number = input.nextInt();
} else {
isItOk = true;
}
}
mark[i][j] = number;
}
}
Spoiler 2 : This is a little nicer code, but for beginners, I would recommend the approach of Spoiler 1, because it is always usable. In more complex problems, the Spoiler 2 solution is not always possible.
for (i = 0; i < maxRow; i++) {
for (j = 0; j < maxCol; j++) {
System.out.print("Please enter ");
int number = input.nextInt();
while (number < 0 || number > 100) {
System.out.println("You shall not insert a value below 0 or bigger than 100! Try it again");
number = input.nextInt();
}
mark[i][j] = number;
}
}
Scanner s = new Scanner(System.in);
int number =0;
System.out.print("Please enter ");
while(true)
{
number = s.nextInt();
if(number > -1 && number < 101)
break;
System.out.println("Marks should be between 0 and 100, Please enter");
}
You also need to validate if input is integer, which can be done through exception handling