I have written a program to check if a number is an Unique number.
[A Unique number is a number with no repeating digits and no leading zeros.]
I have written the following code:
Scanner sc=new Scanner(System.in)
System.out.println("Enter the number to be checked: ");
String num=sc.nextLine();
if(num.charAt(0)!='0')
{
Outer:
for(int i=0;i<num.length();i++)
{
for(int j=0;j<num.length();j++)
{
if(num.charAt(i)==num.charAt(j))
{
System.out.println("No, "+num+" is not a Unique number.");
break Outer;
}
}
if(i==num.length()-1)
{
System.out.println("Yes, "+num+" is a Unique number.");
}
}
}
else
System.out.println("No, "+num+" is not a Unique number as it has leading zeros.");
The problem is that is shows any number as NOT Unique, even 12345.
I would like to know where I have gone wrong.
Your code will always find "duplicate" characters when i == j.
You should change the indices of the loop in order not to compare a character to itself:
for(int i=0;i<num.length();i++) {
for(int j=i+1;j<num.length();j++) {
if(num.charAt(i)==num.charAt(j))
...
Besides, you should only output the "...is a Unique number." message after you are done with the outer loop.
Lets assume , length of input number to be 10 and "i" has reached the value of 5 in the for loop.
Now "j" will have the values 0 to 9.
So when "j" is equal to 5 , the if condition becomes true as you are comparing the digit at 5th position with itself (which is always true).
If you add i != j condition , it will fix the issue :-
if(num.charAt(i)==num.charAt(j) and i != j)
Alternatively, you can modify the loop for j to start from i + 1 so
that there are no overlaps.
for(int j=i+1;j<num.length();j++)
The second option is much better as it will reduce the number of comparisons from (n*n)
to (n * (n - 1))/2) , where n is the number of digits in the input number.
A possible solution is to use Stream to convert your String in a Set of char, then if the size of the set is the same as the length of your string, it is unique:
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number to be checked: ");
String num = sc.nextLine();
boolean unique = Stream.of(num.split(""))
.map(s -> new String(s))
.collect(Collectors.toSet()).size() == num.length();
// With "1234" -> print true
// With "12342" -> print false
System.out.println(unique);
You can use below short and handy approach:
String a = "123452";
String[] split = a.split("");
List<String> list = Arrays.asList(a.split(""));
Set<String> set = new HashSet<>(list);
System.out.println("Unique: " + (list.size() == set.size()));
import java.util.*;
public class spnum
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
String num = sc.next();
int ctr = 0;
boolean isNumUnique = true;
for(int i = 0; i < num.length(); i++)
{
for(int j = 0; j < num.length(); j++)
{
if(num.charAt(i) == num.charAt(j))
{
ctr++;
}
}
if(ctr > 1)
{
isNumUnique = false;
}
ctr = 0;
}
if(isNumUnique == true)
{
System.out.println("Number is a unique number");
}
else
{
System.out.println("Number is not a unique number");
}
}
}
this code would give the right answer
Related
I wanted to make a program in which only repeats words that has 3 of the same letters back to back. eg the mooonkey raaan through the mounnntains. the program should only repeat mooonkey, raaan
public class Triplets2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("write a sentence");
String in = input.nextLine();
String [] sentence = in.split(" ");
for (int i = 0; i < sentence.length; i++) {
char [] word = sentence[i].toCharArray();
int counter =0;
for (int s = 0; s < word.length; s++) {
char letter = word[s];
for (int x = 0; x<word.length; x++) {
if (letter == word[x]) {
counter++;
}
else {
counter = 0;
}
}
}
if (counter >=3) {
System.out.print(sentence[i] + ", ");
}
}
}
the program instead just repeats nothing.
Your code is almost correct, the only logical error you made is inside your inner loop you keep resetting your counter variable as soon as you find a letter that is different:
if (letter == word[x]) {
counter++;
} else {
counter = 0;
}
So when you iterate over a word like "raaan" your counter will reset when it reaches the very end of the String, because "n" only exists once.
What this means is that you will only be able to detect words that have 3 consecutive letters at the very end (like "Hooo").
The solution is simple:
Once you found 3 consecutive letters in a word you can just stop iterating and checking the rest of your word. At that point you already know that it fits your criteria:
if (letter == word[x]) {
counter++;
if(counter >= 3) break; // stop inner loop checking once we found 3 letters
} else {
counter = 0;
}
Since you are looking for consecutive letters you want to start at char i and then compare the char at i to char at i+1 and at i+2. If they are all equal then we have a match and can continue.
You can simplify the whole function such as:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("write a sentence");
String in = input.nextLine();
List<String> tripleLetter = new ArrayList<>();
for (String s : in.split(" ")) {
char[] word = s.toCharArray();
for (int i = 0; i < word.length - 2; i++) {
if ((word[i] == word[i+1]) && (word[i] == word[i+2])) {
tripleLetter.add(s);
break;
}
}
}
System.out.println(tripleLetter.stream().collect(Collectors.joining(", ")));
}
Allow me to suggest a solution that differs slightly from yours and doesn't use a counter.
Scanner input = new Scanner(System.in);
System.out.println("write a sentence");
String in = input.nextLine();
String[] sentence = in.split(" ");
for (int i = 0; i < sentence.length; i++) {
char[] word = sentence[i].toCharArray();
for (int s = 0; s < word.length - 2; s++) {
if (word[s] == word[s + 1] && word[s] == word[s + 2]) {
System.out.print(sentence[i] + ", ");
break;
}
}
}
Check whether the current letter, in the current word, is the same as the next letter and the same as the letter after the next letter. If the condition holds, then print the current word and proceed to the next word in the sentence.
Well, if you're just looking for a shorter version of doing this then try this.
first, split the sentence on one or more white space characters (you should be doing that regardless).
stream the array and filter on a single character, followed by the same two characters via a back reference to the capture group (see regular expressions for that).
And print them.
String str =
"Thiiis is aaaa tesssst of finding worrrrds with more than threeeeee letteeeeers";
Arrays.stream(str.split("\\s+"))
.filter(s -> s.matches(".*(.)\\1\\1.*"))
.forEach(System.out::println);
Prints
Thiiis
aaaa
tesssst
worrrrds
threeeeee
letteeeeers
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
My program is supposed to make sure each value the user enters is between 10-100. The value is then stored in the array. That part works fine. The other condition is that the value the user enters has to be different from all the other arrays. ie...array[0]=20 so all of the other arrays can no longer equal to be set to 20. I've been trying to solve this but I'm just not sure where to go. I tried setting statements after my while(userInput < 10 || userInput > 100) to check for any repeats and that worked. The problem was then the user could enter values less than 10 and greater than 100. Any help would be greatly appreciated!
public static void main(String[] args) {
//Creating scanner object
Scanner input = new Scanner(System.in);
int[] array = new int[5];
int counter = 0;
while(counter < 5)
{
for(int x = 0; x < array.length; x++)
{
System.out.print("Enter number between 10 & 100: ");
int userInput = input.nextInt();
while(userInput < 10 || userInput > 100)
{
System.out.print("Please enter number between 10 & 100: ");
userInput = input.nextInt();
}
array[x] = userInput;
System.out.println(array[x]);
counter++;
}
}
System.out.println();
System.out.println("The value of Array[0]: " + array[0]);
System.out.println("The value of Array[1]: " + array[1]);
System.out.println("The value of Array[2]: " + array[2]);
System.out.println("The value of Array[3]: " + array[3]);
System.out.println("The value of Array[4]: " + array[4]);
}
}
You should get rid of the for and second while loop, and check if the value entered is in the desired range.
If it is, you verify for duplicates, store it in the array and increment the counter. If it’s not, you show the bad input message.
Either way, it continues to ask for an valid input until the counter gets to 5.
I hope it helps!
I changed your logic a little bit, see if you can understand it
(There are better ways of doing this, but I think this is more understandable)
public static void main(String[] args) {
//Creating scanner object
Scanner input = new Scanner(System.in);
int[] array = new int[5];
int counter = 0;
while(counter < 5)
{
System.out.print("Enter number between 10 & 100: ");
int userInput = input.nextInt();
if(userInput < 10 || userInput > 100)
{
System.out.print("Please enter number between 10 & 100.\n");
}
else {
//This is a valid input, now we have to check whether it is a duplicate
boolean isItDuplicate = false;
for(int i = 0; i < counter; i++)
{
if(userInput == array[i])
{
isItDuplicate = true;
}
}
if(isItDuplicate == true)
{
System.out.print("Please enter a number that is not a duplicate.\n");
}
else
{
array[counter] = userInput;
System.out.println(array[counter]);
counter++;
}
}
}
System.out.println();
System.out.println("The value of Array[0]: " + array[0]);
System.out.println("The value of Array[1]: " + array[1]);
System.out.println("The value of Array[2]: " + array[2]);
System.out.println("The value of Array[3]: " + array[3]);
System.out.println("The value of Array[4]: " + array[4]);
}
Don't use variable counter when var x does the same thing for you.
Don't use nested loops when the limiting condition of both loops need to be checked together in each iteration. Merge those loops into one wherever possible.
First of all, get rid of your nested loops. They're redundant. Let's look at your problem's specification. Your input needs to fulfill 3 requirements:
Be greater than or equal to 10
Be less than or equal to 100
Be a unique element inside the array
The first two conditions are simple enough to check. For the final condition, you need to search the values inside the array and see if there are any matches to your input. If so, the input is invalid. A simple way to approach this is to check every member of the array and to stop if a duplicate is found. There are better, more efficient ways to do this. Don't be afraid to search the internet to learn a searching algorithm. Below is a simple solution to your problem. It's far from ideal or efficient, but it's easy enough for a beginner to understand.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] array = new int[5];
int counter = 0;
int userInput;
while(counter < 5) {
System.out.print("Enter a number between 10 & 100: ");
userInput = in.nextInt();
if( (userInput >= 10 && userInput <= 100) && !searchDuplicates(array, userInput) ) {
array[counter] = userInput;
counter++;
} else {
System.out.println("Invalid value entered");
}
}
for(int i = 0; i < array.length; i++)
System.out.println("Value " + (i + 1) + ": " + array[i]);
}
private static boolean searchDuplicates(int[] array, int input) {
for(int i = 0; i < array.length; i++)
if(array[i] == input)
return true;
return false;
}
}
I have a task with checking ID number and I must check if this ID has 11 characters, if those characters are digits and I must check control number. Number is correct when this equation is correct:
ID = abcdefghijk
(1*a+3*b+7*c+9*d+1*e+3*f+7*g+9*h+1*i+3*j+1*k) % 10 = 0
Sample correct ID is: 49040501580
And here is my program. I don't know how to check if ID is digit and why it isn't correct. Anyone help? XD
Thank you in advance :3
import java.util.*;
public class wat {
public static void main(String[] args) {
char[] weights = {1, 3, 7, 9, 1, 3, 7, 9, 1, 3, 1};
System.out.print("Enter next digits your ID number: ");
Scanner keyboard = new Scanner(System.in);
String number = keyboard.nextLine();
char[] ofm = number.toCharArray();
Character[] id = new Character[ofm.length];
for (int i = 0; i < ofm.length; i++) {
id[i] = ofm[i];
System.out.print(id[i] + " ");
int length = id.length;
if (length == 11) {
System.out.println("This ID number has 11 digits");
System.out.println("Checking of the control number");
int amount = 0;
amount = id[i] * weights[i];
System.out.println(amount);
int result = 0;
result = amount % 10;
if (result == 0) {
System.out.println("ID number is correct");
} else {
System.out.println("ID number is not correct");
break;
}
} else {
System.out.print("This ID number hasn't 11 digits.");
break;
}
}
}
}
Sample output
With a minimal number of changes to your original code, I believe this is what you need.
import java.util.*;
public class wat {
public static void main(String[] args) {
char[] weights = {1,3,7,9,1,3,7,9,1,3,1};
System.out.print("Enter next digits your ID number: ");
Scanner keyboard = new Scanner(System.in);
String number = keyboard.nextLine();
char[] ofm=number.toCharArray();
Character[] id=new Character[ofm.length];
if (ofm.length == 11) {
System.out.println("This ID number has 11 characters");
int amount = 0;
for (int i = 0; i < ofm.length; i++) {
id[i]=ofm[i];
System.out.print(id[i]+" ");
int length = id.length;
if (isDigit(id[i])) {
amount = id[i]*weights[i];
} else {
System.out.println("character is not a digit");
break;
}
}
} else {
System.out.print("This ID number hasn't 11 digits.");
return;
}
System.out.println("Checking of the control number");
System.out.println(amount);
int result =0;
result = amount % 10;
if (result == 0) {
System.out.println("ID number is correct");
} else {
System.out.println("ID number is not correct");
}
}
}
As you can see, we're now verifying the string length before the loop starts.
Then we're checking each character is a digit one by one and quitting with a new error message if one of them is not. You'll need to provide the isDigit function yourself (plenty to choose from on StackOverflow!).
We're accumulating the digit values multiplied by the weight into the amount variable, with a new value being added each time the loop iterates.
Finally we verify the result is correct after the loop has finished and all 11 characters have been processed.
NOTE: I don't normally work in Java so I'm not entirely sure if you can get the digit value out of a Character type object (to multiply it with the weight) like this. You might find that you are getting ASCII code values, or something else entirely. If this happens, you'll need to convert 'weights' into an array of integers, and extract the actual numeric value from the Character before multiplying them together.
I'm trying to ask the user to enter any number of numbers up to 5, each number seperated by space.
for example
enter up to 5 numbers : 3 4 5
I'm going to add them in the integer sum and then later divide them by counter
to get the average of these numbers.
However, my loop does not seem to end. What's wrong with my code?
int counter = 0 , sum = 0;
Scanner scan = new Scanner(System.in);
System.out.println("enter up to 5 numbers");
while(scan.hasNextInt());{
counter++;
sum += scan.nextInt();
}
System.out.println(counter);
System.out.println(sum);
You put a ; between while and {, so it loops. Remove it.
Scanner.hasNextInt() does not do what you seem to think it does. It does not tell you whether there is an integer available in already typed input (it does not have any conception of what has "been typed"), but rather whether the input waiting can be read as an integer. If there is no input already waiting, it will block until there is, so your loop is simply sitting there forever, blocking for more input.
What you probably want to do instead is to read a whole line, and then split it explicitly into space-separated parts, and only then parse those as integers. For example, like this:
String input = scan.nextLine();
for(String part : input.split(" "))
sum += Integer.parseInt(part);
Serge Seredenko's answer is also correct, however, but that's another problem.
Everything in your code is fine except the semicolon(;) just after the while loop, of course it will lead to an infinite loop.
int counter = 0 , sum = 0;
Scanner scan = new Scanner(System.in);
System.out.println("enter up to 5 numbers");
while(scan.hasNextInt()){
counter++;
sum += scan.nextInt();
if(counter >=5)
break;
}
System.out.println(counter);
System.out.println(sum);
scan.close();
First, you need to remove ';' located after while(scan.hasNextInt()) and before {; For the ; means the while statement is complete.
Second, when you use your code, you need CTRL + Z to end up your input. By adding
if(counter >=5)
break;
your input will end up when you input 5 numbers.
If you want to read entire line and then do arithmetic operation later then you dont need to have while loop with hasNextInt() method.
I would suggest you to read line then split by space and iterate over string array. Check out code snippet.
package com.gaurangjadia.code.java;
import java.util.Scanner;
public class SO19204901 {
public static void main(String[] args) {
int counter = 0,
sum = 0;
System.out.println("enter up to 5 numbers");
Scanner scan = new Scanner(System.in);
String strInput = scan.nextLine();
String[] arrayNumbers = strInput.split(" ");
for (int i = 0; i < arrayNumbers.length; i++) {
int n;
try {
n = Integer.parseInt(arrayNumbers[i]);
}
catch (NumberFormatException e) {
n = 0;
}
sum = sum + n;
counter++;
}
System.out.println(sum);
}
}
DataInputStream in = new DataInputStream(System.in);
String[]label = {"quiz #","Total","Average"};
int counter = 0;
int theSum = 0;
System.out.print("Enter up to 5 number : ");
String[]tempNum = in.readLine().trim().split("\\s+");
System.out.println();
while (counter <= tempNum.length)
{
if ( counter == tempNum.length)
{
System.out.printf("%10s %12s\n",label[1],label[2]);
counter = 0;
break;
} else {
System.out.printf("%10s",label[0] + (counter+1) );
}
counter++;
}
while(counter <= tempNum.length)
{
if ( counter == tempNum.length)
{System.out.printf("%10d %10.2f\n",theSum,(double)(theSum/counter));
} else
{System.out.printf("%10d",Integer.valueOf(tempNum[counter]));
theSum += Integer.valueOf(tempNum[counter]);
}
counter++;
}