Program about how many times the number has been repeated - java

For example i want to find how many times 1 repeated in number 123900148
It must be write 2 times but i get wrong values for everytime
Scanner input = new Scanner(System.in);
#author Başar Ballıöz
int counter = 0;
int repeat;
int tmp;
System.out.print("Enter A Number: ");
tmp = input.nextInt();
String number = Integer.toString(tmp);
System.out.print("Enter A Number You Want To Find: ");
repeat = input.nextInt();
for (int i = 0; i < number.length() - 1 ; i++) {
if (number.substring(i , i+1).equals(repeat))
counter++;
}
System.out.println(repeat + " number " + counter + " repeated.");
i would like to see my output like:
number : 134211
number i want to find how many times repeated: 1
your number has repeated 3 times

You are comparing a String (returned by number.substring(i , i+1) to an Integer, so of course it will always return false.
Either compare two ints or two Strings. Since you are essentially comparing two digits, comparing ints would be more efficient.
for (int i = 0; i < number.length(); i++) {
if (Character.getNumericValue(number.charAt(i)) == repeat) {
counter++;
}
}

Scanner input = new Scanner(System.in);
int counter = 0;
int repeat;
int tmp;
System.out.print("Enter A Number: ");
tmp = input.nextInt();
String number = Integer.toString(tmp);
System.out.print("Enter A Number You Want To Find: ");
repeat = input.nextInt();
while (tmp > 0) {
if (tmp % 10 == repeat) {
counter++;
}
tmp = tmp/10;
}
System.out.println(number + " number " + counter + " repeated.");

You're comparing a String against an Integer via equals hence you're not getting the expected result. instead convert the integer to a string prior to comparison:
if (number.substring(i , i+1).equals(String.valueOf(repeat)))
Further, you could cache the result of String.valueOf(repeat) into a variable before the for loop to prevent a string object construction in each iteration of the loop.

Try this. I added some helpful output so you can see how it's indexed.
import java.util.Scanner;
import java.util.Map;
import java.util.HashMap;
public class CountChars {
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter A String: ");
Map<String, Integer> map = indexString(input.nextLine());
while (true) {
System.out.print("Enter A Character You Want To Count (ENTER to exit): ");
String repeat = input.nextLine();
if (repeat == null || repeat.isEmpty()) {
break;
}
System.out.println(String.format("'%s' was repeated %d time(s).", repeat, (map.containsKey(repeat)) ? map.get(repeat):Integer.valueOf(0)));
}
}
private static Map<String, Integer> indexString(String s) {
Map<String, Integer> map = new HashMap<>();
System.out.println(String.format("'%s' has %d characters. Indexing now.", s, s.length()));
for (int i = 0; i < s.length() ; i++) {
String c = String.valueOf(s.charAt(i));
if (!map.containsKey(c)) {
map.put(c, 0);
System.out.println(String.format("Indexing %s", c));
}
System.out.print(String.format("Incrementing '%s' from %d ", c, map.get(c)));
map.put(c, map.get(c) + 1);
System.out.println(String.format("to %d.", map.get(c)));
}
return map;
}
}

Related

How do I find the number of occurences of repeating elements in array in Java EE?

I tried writing a code fragment to find the number of occurences of a repeating element in a 1 dimensional array in Java....the counter doesnt seem to go above 1...could someone help me please..
here is my code:
import java.util.*;
public class duplicate{
public static void main(String args[]){
int i,n,c,j,m=-1;
Scanner a = new Scanner(System.in);
System.out.println("Enter the value of length");
n=a.nextInt();
int b[] = new int[n];
System.out.println("Enter the elements of the array.");
for(i=0;i<n;++i)
b[i]=a.nextInt();
for(i=0;i<n;++i){
c=0;
if(b[i]==m)
continue;
else{
m=b[i];
for(j=0;j<=i;++j){
if(b[j]==b[i])
c++;
}
System.out.println("The element"+b[i]+" has occured "+c+" times.");
}
}
}
}
There are many things sketchy with your code snippet. First of all, I would advise you to properly format your code and maybe improve some variable naming.
I took the portion of your code to show it is buggy:
for (i = 0; i < n; ++i) {
c = 0;
if (b[i] == m) {
continue;
} else {
/*
* here you always set m to the current value of the array so in the next
* iteration, your check in the "if clause" will be true what means that the
* counter will never count up if there are 2 or more consecutive equal numbers
*/
m = b[i];
for (j = 0; j <= i; ++j) {
// also this logic is flawed, because you only count the values
// before the current one
if (b[j] == b[i])
c++;
}
System.out.println("The element" + b[i] + " has occured " + c + " times.");
}
}
What i would rather advise you to use for this kind of task, is to use a HashMap and count the occurrences for each value there.
Example:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the value of length");
int size = scanner.nextInt();
int[] values = new int[size];
System.out.println("Enter the elements of the array.");
for (int i = 0; i < size; i++) {
values[i] = scanner.nextInt();
}
Map<Integer, Integer> map = new HashMap<>();
for (int key : values) {
if (map.containsKey(key)) {
int occurrence = map.get(key);
occurrence++;
map.put(key, occurrence);
} else {
map.put(key, 1);
}
}
for (Integer key : map.keySet()) {
int occurrence = map.get(key);
System.out.println(key + " occurs " + occurrence + " time(s).");
}
}

How can I print to the console this table of numbers in Java?

Asking for a natural number n, I want to print to the console in this format:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
.
.
.
n . . . 5 4 3 2 1
Inputting 4, this is what I have so far:
1
21
321
4321
I want to add a space between the numbers. This is my code:
import java.util.Scanner;
public class PatternTwo {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int userInput;
System.out.println("Please enter a number 1...9 : ");
userInput = in.nextInt();
String s="";
int temp = userInput;
for(int i=1; i<=userInput; i++ ) {
for (int k= userInput; k>=i; k-- ) {
System.out.printf(" ");
}
for(int j =i; j>=1; j-- ) {
System.out.print(j);
}
System.out.println("");
}
}
}
Add a space in front of the number to be printed and double the spaces above so that it is not a pyramid. Something like this:
import java.util.Scanner;
public class PatternTwo {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int userInput;
System.out.println("Please enter a number 1...9 : ");
userInput = in.nextInt();
String s="";
int temp = userInput;
for(int i=1; i<=userInput; i++ ) {
for (int k= userInput; k>i; k-- ) { // <- corrected condition
System.out.printf(" ");
}
for(int j = i; j>=1; j-- ) {
System.out.print(j);
// check if not 1 to avoid a trailing space
if (j != 1) {
System.out.print(" ");
}
}
System.out.println("");
}
}
}
EDIT
Thanks to /u/shash678 I corrected my solution to remove all unnecessary or wrong spaces
How about a cleaner solution, which avoids using nested for-loops:
public static void main(final String[] args) {
final Scanner scanner = new Scanner(System.in);
System.out.print("Please enter a number 1...9 : ");
final int n = scanner.nextInt();
final ArrayList<String> suffixes = new ArrayList<>();
for (int i = 1; i <= n; i++) {
suffixes.add(0, i + " ");
final String prefix = String.join("", Collections.nCopies(n - i, " "));
final String suffix = String.join("", suffixes);
System.out.println(prefix + suffix);
}
}
Below is a modification of your answer that does not print unnecessary extra white space when k equals i by modifying your k for-loops exit condition and similarly when j equals i by dealing with that case separately.
The main overall change is that in your k-loop you need to print 2 spaces rather than 1 to achieve your desired right side alignment:
import java.util.Scanner;
class PatternTwo {
private static void printPatternTwo(int n) {
for (int i = 1; i <= n; i++) {
for (int k = n; k > i; k--) {
System.out.print(" ");
}
for (int j = i; j >= 1; j--) {
System.out.print(j == i ? j : " " + j);
}
System.out.println();
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter an integer between 1 and 9 inclusive: ");
int userNum = -1;
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
userNum = scanner.nextInt();
if (userNum >= 1 && userNum <= 9) {
scanner.close();
break;
} else {
System.out.println("ERROR: Input number was not between 1 and 9");
System.out.print("Enter a single digit number: ");
}
} else {
System.out.println("ERROR: Invalid Input");
System.out.print("Please enter an integer between 1 and 9 inclusive: ");
scanner.next();
}
}
printPatternTwo(userNum);
}
}
Example Usage:
Please enter an integer between 1 and 9 inclusive: 12
ERROR: Input number was not between 1 and 9
Enter a single digit number: a
ERROR: Invalid Input
Please enter an integer between 1 and 9 inclusive: 5
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
When printing the number put a space in from of it.
// this works up n == 9
System.out.print(" " + j);
For n > 9 the issue is that you need to print the number and whitespaces on a fixed amount of space however the number of chars a number contains changes. A solution would be to use tab (or several if you want really big numbers).
// when printing blank spaces use a tab instead
for (int k= userInput; k>=i; k-- ) {
System.out.printf("\t");
}
// then print number with tab in front
for(int j =i; j>=1; j-- ) {
System.out.print("\t"+j);
}
If you are comfortable with streams:
public class PatternTwo {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int userInput;
System.out.println("Please enter a number 1...9 : ");
userInput = in.nextInt();
String s = "";
int temp = userInput;
revRange(1, temp).forEach(n -> printNumbers(n, temp));
}
static IntStream revRange(int from, int to) {
return IntStream.range(from, to)
.map(i -> to - i + from - 1);
}
private static void printNumbers(int n, int max) {
IntStream.rangeClosed(0, n -1)
.forEach(num -> System.out.print(" "));
revRange(1, max - n)
.forEach(num -> System.out.print(num + " "));
System.out.println();
}
}
Another alternative way could be to separate the spacing for each line using printf
and using String.format for each number.
String.format("%1$" + length + "s", inputString)
returns the inputString if inputString.length >= lengthelse the inputString padded with spaces so that the length equal to the given length.
Example:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int userInput;
System.out.println("Please enter a number 1...9 : ");// you can use this also for numbers > 9
userInput = in.nextInt();
int digits = String.valueOf(userInput).length()+1;
for(int i = 1; i<=userInput; i++){
System.out.printf("%1$"+(digits*(userInput-i+1))+"s","");
for(int k = userInput - (userInput-i); k >= 1; k--){
System.out.print(String.format("%1$"+digits+"s", k));
}
System.out.println();
}
}

String of only even numbers and only odd numbers

I know there are already questions asking something similar to my question, but despite reading those, they don't quite do what I want.
I am creating a code that takes a users input of a number between 0-100 (inclusive). Whatever the number, it will print all the numbers leading up to that number and that number
EX: user input = 25
output = 012345678910111213141516171819202122232425
I have that part working. Now I am supposed to use that string and create two new strings, one for only the odd and the other one for the even numbers.
EX: user input = 25
output: odd numbers: 135791113151719212325 & even numbers = 024681012141618202224
Here is my code so far:
import java.util.Scanner;
public class OddAndEven{
public String quantityToString() {
Scanner number = new Scanner(System.in);
int n = number.nextInt();
String allNums = "";
if ((n >= 0) && (n <= 100)) {
for (int i = 0;i <= n; ++i)
allNums = allNums + i;
return allNums;
}
else {
return "";
}
}
public void oddAndEvenNumbers(int num) {//Start of second method
String allNums = ""; //String that quantityToString returns
String odd = "";
String even = "";
if ((num >= 0) && (num < 10)) { //Looks at only single digit numbers
for (int i = 0; i <= allNums.length(); i++) {
if (Integer.parseInt(allNums.charAt(i))%2 == 0) { //trying to get the allNums string to be broken into individual numbers to evaluate
even = even + allNums.charAt(i); //adding the even numbers of the string
}
else {
odd = odd + allNums.charAt(i);
}
}
}
else { //supposed to handle numbers with double digits
for (int i = 10; i <= allNums.length(); i = i + 2) {
if (Integer.parseInt(allNums.charAt(i))%2 == 0) {
even = even + allNums.charAt(i);
}
else {
odd = odd + allNums.charAt(i);
}
}
}
System.out.println("Odd Numbers: " + odd);
System.out.println("Even Numbers: " + even);
}
public static void main(String[] args) {
System.out.println(new OddAndEven().quantityToString());
//System.out.println(new OddAndEven().oddAndEvenNumbers(allNums));
//Testing
OddAndEven obj = new OddAndEven();
System.out.println("Testing n = 5");
obj.oddAndEvenNumbers(5);
System.out.println("Testing n = 99");
obj.oddAndEvenNumbers(99);
I know my problem is at the part when its supposed to take the string apart and evaluate the individual numbers, but I don't know what to do. (I've also tried substring() & trim()) Also I have not learned how to use arrays yet, so that is why I did not try to use an array.
I think you can make it that way:
int x = 20;
StringBuilder evenNumberStringBuilder = new StringBuilder();
StringBuilder oddNumberStringBuilder = new StringBuilder();
for(int i =0 ; i<x+1; i++){
if(i % 2 == 0)evenNumberStringBuilder.append(i);
else oddNumberStringBuilder.append(i);
}
System.out.println(evenNumberStringBuilder);
System.out.println(oddNumberStringBuilder);
Output:
02468101214161820
135791113151719
you are already taking the input as integer, so don't work with strings. I recommend that to use this loop;
Scanner number = new Scanner(System.in);
System.out.print("Even Numbers: ");
for (int i = 0; i <= number; i=i+2) {
System.out.print(i);
}
System.out.println("");
System.out.print("Odd Numbers: ");
for (int i = 1; i <= number; i=i+2) {
System.out.print(i);
}
You can simply evaluate numbers while storing them in an allnumbers string, here's a functioning code:
int x = 23; //user input
String s=""; //contains all numbers from 0 to userinput
String odd =""; //contains all odd numbers from 0 to userinput
String even = ""; //contains all even numbers from 0 to userinput
for(int i = 0 ; i< x+1 ; i++){
s += i;
if(i%2==0) //if i is an even number
even += i;
else //if i is an odd number
odd += i;
}
System.out.println(s); //displaying all numbers from 0 to user input
System.out.println(odd); //displaying odd numbers from 0 to user input
System.out.println(even); //displaying even numbers from 0 to user input

Last word/sentence on an Array Java

I have an assignment, it looks pretty easy however I cannot figure it out how to solve it.
It says:
a) Ask the user: How many words/sentences do you want to write (at
least 5) ? (Use while loop)
b) Use for loop to make the user write the words/sentences
c) After the user's written the words/sentences, output which
word/sentence comes last alphabetically (using .compareTo() method )
This is what I came up with:
import java.util.Scanner;
import java.lang.String;
import java.util.Arrays;
public class LastString {
public static void main (String [] args){
Scanner input = new Scanner (System.in);
final short MIN_NUM = 2;
int num = 0;
int count = 0;
String [] sentence = new String [0];
String last = "";
while (num < MIN_NUM){
System.out.println("How many words/sentences do you want to put? " + "\t\t\t\t\t\t\t\t --- at least " + MIN_NUM);
num = input.nextInt();
sentence = new String [num];
}
for (int i = 0; i < num ; i++ ) {
System.out.println("\nWrite a word/sentence" + "\t\t\t\t\t\t\t\t\t --- (Time: " + (i+1) + " )");
sentence [i] = input.nextLine();
System.out.println("The word/sentence is: " + sentence[i]);
}
int i = 0;
int max;
for (i=0;i<num-1 ;i++ ) {
if(sentence[i].compareTo(sentence[i+1]) > 0){
last = sentence[i];
count ++;
}else if (sentence[i].compareTo(sentence[i+1]) < 0) {
last = sentence[i+1];
count++;
}
}
System.out.println("\n\n------------" +
"\nLast word/sentence is: " + last);
System.out.println(Arrays.toString(sentence));
}
}
I compiles and runs. I have two problems:
nextLine >>> it is skiping the first Sentence
I don't know how to make the algorithm to calculate which word/sentence has the biggest value or, using the compareTo() method which word/sentence has the value > 0 compared to each and every other value on the array.
Thank you.
Answer to Q1 : num = input.nextInt(); takes a number as the input but doesn't also consume the new-line, and hence the nextLine consumes the empty new line ... you could use input.nextLine also to get the first number instead of num = input.nextInt(); by reading a line, then parsing the int value as num = Integer.parseInt(input.nextLine());
Answer to Q2 :
You re-set the value of last everytime but you don't compare the value of the next biggest candidate with the last before re-assigning last ...
for example, look at the following :
for (int i = 0; i < num - 1; i++) {
String thisLast = "";
if (sentence[i].compareTo(sentence[i + 1]) > 0) {
thisLast = sentence[i];
count++;
} else if (sentence[i].compareTo(sentence[i + 1]) < 0) {
thisLast = sentence[i + 1];
count++;
}
if (thisLast.compareTo(last) > 0)
last = thisLast;
}
it will solve your problem....
int count = 0;
String [] sentence = new String[6];
String last = "";
for (int i = 0; i < num ; i++ ) {
System.out.println("\nWrite a word/sentence" + "\t\t\t\t\t\t\t\t\t --- (Time: " + (i+1) + " )");
sentence [i] = input.nextLine();
count++;
if(count >= 2){
if(sentence[i].compareTo(last) > 0){
last = sentence [i] ;
}
}else{
last = sentence [i];
}
System.out.println("The word/sentence is: " + sentence[i]);
}

Getting a sum from a while loop

I am trying to get the sum of even numbers between 2 and a value entered by the user. I managed to get as far as printing out the even numbers but how would I get it to print just a sum of the even numbers? Rather than listing out all of the even numbers?
At the end it should look like this:
Entered value: 20
Sum of even numbers between 2 and 20: 110
import java.util.Scanner;
public class Practice_7_1
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
while (true)
{
//Gather data value
System.out.println("Please enter a number: ");
int value = input.nextInt();
String text = "Sum of even numbers between 2 and " + value + " is: ";
//Loop
int i = 2;
while (i <= value)
{
if (i%2 == 0){
text = (text + i);
if (i< value)
text = (text + ", ");
else
text = (text + ". ");
}
i++;
}
//Output
System.out.println(text);
}
}
}
Edit:
Final answer:
import java.util.Scanner;
public class Practice_7_1
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
while (true)
{
//Gather data value
System.out.println("Please enter a number: ");
int value = input.nextInt();
String text = "Sum of even numbers between 2 and " + value + " is: ";
//Loop
int sum = 0;
for (int i = 2; i <= value; i +=2){
sum += i;
}
//Output
System.out.print(text);
System.out.println(sum);
}
}
}
Use a for loop. With a for loop, you can customize the "step" of your internal loop variable (i). This also removes the need to check for even-ness.
int sum = 0;
for (int i = 2; i < value; i+=2) {
sum += i;
}
System.out.println(sum);
On a side note, you should probably avoid the use of while(true) because it's going to require the use of an explicit break to exit the program. You should instead use some sort of boolean control variable.

Categories

Resources