I'm having a huge problem here. Basically what i have to do is have a user enter a number... the program then takes the number, reads if it's negative or positive. If negative it sets the previously false negval to true and moves on. it then reads the number again, checking for leading zeros, if there are any it removes them. It then takes what is left and checks to see if the string is less than the max amount of characters aloud, if it is then it loops to count the spaces, while it counts the spaces it also makes sure they are digits . if the string is bigger than the allowed amount of characters the program stops checks and prints a 0
my problem is that it keeps jumping to the 0 output even though the string length is a valid length
here is what i have.
String snum;
System.out.print("Please enter a number here : ");
snum = console.next();
System.out.println(getIntnum(" The number entered was: "+snum));
Other generic stuff
final String maxInt = "2147483648";
final String minInt = "-2147483648";
boolean negval = false;
int n;
int count;
int num = 1;
int value;
if(snum.charAt(0) == '-' || snum.charAt(0) == '+')
{
if(snum.charAt(0) == '-')
{
negval = true;
}
else
{
snum = snum.substring(1, snum.length());
}
}
while (snum.charAt(0) == '0')
{
snum = snum.substring(1, snum.length());
}
n = snum.length( );
if (n < 10)
{
count = 0;
if (count < n)
{
if (Character.isDigit(snum.charAt(count)))
count++;
}
}
else
{
num = 0;
}
if(maxInt.compareTo(snum) >= 0 && minInt.compareTo(snum) <= 0)
{
num = Integer.parseInt(snum);
}
if(negval == true)
{
num = num * -1;
}
value = num;
return value;
}
}
You are comparing Strings which don't work the same way as comparing numbers. For example, "10" < "2" because '1' < '2' and this means that "-1" < "-2147483648" and "3" > "2147483647"
It's difficult to suggest what you should do instead as it's not clear to me why you are doing half of the code you have e.g. Can you say how your code is different from
try {
return Integer.parseInt(s);
} catch (NumberFormatException ignored) {
return 0;
}
Your main problem is that you're using a string comparison to compare numbers. Also, since you already know that the number is positive, there's not much point comparing it to minInt. Lastly, you have the wrong value for maxInt.
Simply use Integer.parseInt(snum)
final String maxInt = "2147483648";
MAX_INT is 2147483647.
Second of all, do not use String comparison to compare numbers. Use it like this:
if (Integer.parseInt(maxInt) >= Integer.parseInt(snum)) {
num = Integer.parseInt(snum);
}
Related
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
I am trying to write a program that will check if the user-entered string is a binary number, and if it is, it will output the number of 1s in the number. I had this working fine with an integer value, but since an int can't hold more than 2 billion or whatever the max value is, I am trying to rewrite it to work with Strings.
As of right now, any number I enter will output "Number entered is not binary." and when I enter 0, I will get a StringIndexOutofBoundsException. I am a fairly novice programmer, so forgive any obvious errors I may have missed, I am just asking for a possible solution to my problem or a push in the right direction. Here is my code (after trying to make it work with Strings rather than integers):
import java.util.*;
public class BinaryHW {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String bin = kb.nextLine();
//the method I used to check whether or not user entered a binary
//number requires changing the value of 'bin'.
//Therefore, 'origBin' set equal to 'bin' for later use.
String origBin = bin;
int count = 0;
boolean isBinary = true;
/* if bin = 0, then this loop will be skipped because
* 0 is a binary number and need not be checked.
*/
while (Integer.parseInt(bin) != 0) {
int lastDigit = bin.charAt(bin.length() - 1);
if (lastDigit > 1) {
System.out.println("Number entered is not binary.");
isBinary = false;
break;
} else {
bin = bin.substring(bin.length() - 2);
}
}
//Again, the method I used to count the 1s in the bin number
//requires changing the value of origBin, so origBin2 is introduced
String origBin2 = origBin;
for (int i = 0; i < origBin.length(); i++) {
if (origBin.charAt(origBin.length() - 1) == 1) {
count ++;
origBin2 = origBin.substring(origBin2.length() - 2);
} else {
origBin2 = origBin.substring(origBin2.length() - 2);
}
}
if (isBinary)
if (count == 1)
System.out.println("There is "
+ count + " 1 in the binary number entered.");
else
System.out.println("There are "
+ count + " 1s in the binary number entered.");
}
}
I think you are overcomplicating things... simply iterate through your binary string, and keep track of the number of 1's reached. If a number other than 0 or 1 is found, report that input is a non-binary number. Below is a snippet which accomplishes this:
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("Enter a binary number: ");
String bin = kb.nextLine();
int oneCount = 0;
boolean validBinaryNum = true;
for (int i = 0; i < bin.length() && validBinaryNum; i++) {
char currentChar = bin.charAt(i);
if (currentChar == '1') oneCount++;
else if (currentChar != '0') {
validBinaryNum = false;
}
}
if (validBinaryNum && bin.length() != 0) {
System.out.println("Number of 1's: " + oneCount);
} else {
System.out.println("Number is not binary");
}
}
The method CountQiftPositiv is returning 0 no matter what inputs I type. What am I doing wrong here?
import java.util.Scanner;
public class QiftPositivCount
{
public static void main(String [] args)
{
Scanner scan = new Scanner(System.in);
final int SENTINEL = -9999;
int x = 0;
int count = 0;
do
{
System.out.print("Type numbers (-9999 to end) : ");
x = scan.nextInt();
if(x == SENTINEL)
{
break;
}
count++;
}while (x != SENTINEL);
if(count == 0)
{
System.out.println("You didnt type any number");
}
else
{
System.out.println("There are " + count + " numbers typed , and the numbers that fulfill the conditon are "
+ CountQiftPositiv(x));
}
}
private static int CountQiftPositiv(int nr)
{
int poz = 0;
if(nr % 2 == 0 && nr % 3 == 0 && nr > 0)
{
poz++;
}
return poz;
}
}
Your do-while loop throws out all user input except the last integer entered (if any). Since the only way out of that loop (not counting exceptions) is the sentinel value -9999, that is the only value you will ever assign to x and pass to CountQiftPositiv.
CountQiftPositiv, meanwhile, only returns 1 if for positive integers divisible by 6. For every other value, including your sentinel, it returns 0.
Other Sentinel Problems
The use of a sentinel value is almost always a mistake (unless that's specifically part of your assignment). Sooner or later, that "impossible" input will actually show up.
Since your goal is to continue the loop until the user is done (a "yes or no" question), use a local Boolean variable, and test that. Also, java.util.Scanner has lots of useful methods for exactly this kind of situation, for example:
boolean done = false;
while (! done) {
if (scan.hasNextInt()) {
// Store scan.nextInt() for use later. See below.
} else {
// No more (valid) inputs.
done = true;
}
}
This loop could actually be shortened to just while (scan.hasNextint()) { ... }, but storing your loop's continue-or-end condition in a variable is handy for more complex exit decisions.
Storing User Input
You aren't storing more than one user input, ever. Create a List of some sort to store them, and then operate on that list.
java.util.List<Integer> numbers = new java.util.LinkedList<Integer>();
Later, in the "while not done" loop:
if (scan.hasNextInt()) {
numbers.add(scan.nextInt());
} else {
done = true;
}
Counting User Inputs
No need for count --- your collection of integers will store that for you:
if (numbers.size() == 0) {
System.out.println("You didn't type any numbers!");
}
Printing Output
Finally, output each number only if it fulfills that weird condition. This assumes you rewrite CountQiftPositiv to return a boolean (which it almost does already):
for (int number : numbers) {
if (CountQiftPositiv(number)) {
System.out.println(number);
}
}
You'll probably want to rename that method now that it no longer counts anything.
I leave the rest to you.
PS: It's almost always a good idea to separate input, processing, and output into (at least) three different methods, especially when you're learning. It's vastly easier to understand a bunch of short methods than one do-it-all method, and makes debugging problems like this much easier.
You have return 0 because last input is -9999 a negative number, and this condition if(nr % 2 == 0 && nr % 3 == 0 && nr > 0) is usually false.
Try to change the SENTINEL nymber:
You're using CountQiftPositiv(x) outside of the while loop.
With the code you have, it's the same thing as you call CountQiftPositiv(-9999)
I'm suggesting you to do something like:
do {
System.out.print("Type numbers (-9999 to end) : ");
x = scan.nextInt();
if(x == SENTINEL) {
break;
}
if (CountQiftPositiv(x) > 0) {
count++;
}
} while (x != SENTINEL);
I suggest also to rework your loop since the break is not required if you use the x = scan.nextInt(); wisely.
CountQiftPositiv(x) sends -9999 in because its the last x value always -> as you stop taking inputs when x = -9999
nr < 0 -> poz will stay at 0
I've made a temp variable which will take your input, if the input is not equal to the SENTINEL variable, it will set x = temp thus removing the -9999 value from being passed into CountQiftPositiv().
Also when you are checking for a number that is a factor for multiple numbers, all you have to do is multiply the numbers together and check the mod for that number.
For 2 and 3, all you have to check is 6.
import java.util.Scanner;
public class QiftPositivCount {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
final int SENTINEL = -9999;
int temp;
int x = 0;
int count = 0;
do {
System.out.print("Type numbers (-9999 to end) : ");
if((temp = scan.nextInt()) == SENTINEL){
break;
}else {
x = temp;
count++;
}
} while (temp != SENTINEL); // not really needed as you have the break statement
if (count == 0) {
System.out.println("You didnt type any number");
} else {
System.out.println("There are " + count + " numbers typed , and the numbers that fulfill the conditon are "
+ CountQiftPositiv(x)); // This was sending -9999 which will always evaluate to false in the function
//poz will stay at 0 the entire time
}
}
private static int CountQiftPositiv(int nr) {
int poz = 0;
//if(nr % 6 && nr > 0){
if (nr % 2 == 0 && nr % 3 == 0 && nr > 0) {
poz++;
}
return poz;
}
}
import java.util.Scanner;
public class lesserString2 {
public static void main(String args[]) {
Scanner r = new Scanner(System.in);
int y = 0;
int result = 0;
String s = null;
String q = null;
while (y < 2) {
s = r.nextLine();
y = y + 1;
q = r.nextLine();
y = y + 1;
}
if (y >= 2){
result = s.compareTo(q);
}
if(result == 0) {
System.out.println("The strings are equal, please try again.");
} else if(result == 1) {
System.out.println("Lesser is: " + s);
} else if(result < 0) {
System.out.println("Lesser is: " + q);
}
}
}
I am getting mixed results when I try to submit two different sentences through standard input.
For instance...
C:\Users\...>java lesserString2
how does the cat jump
very quickly i think
Lesser is: very quickly i think
C:\Users\...>java lesserString2
Jack Sprat can eat no fat
His wife can eat no lean
Why didn't it work the second time? How can I make it work every time? The second one I tried literally outputs nothing... It is just a blank line.
The two main issues are that you're using result == 1 where you need to be using result > 0 (the positive value from compareTo may not be 1; more in item #3.2 below), and that you have your comparisons backward, so you're actually showing the "greater" of the two strings rather than the lesser (item #3.1).
But that code has a variety of other issues, here's a list:
The while (y < 2) loop is completely unnecessary: y starts at 0 and you add 1 to it twice, so it will always execute exactly once.
The if (y >= 2) branch is completely unnecessary (see #1).
You're misusing the return return value of compareTo in two different ways:
When you get a value greater than 0, you're saying s is the "lesser" string. That value indicates s is the greater string.
You're comparing it == 1, but compareTo's contract does not guarantee that it will be 1, just that it will be a positive number if s is greater than q, 0 if they're equal, or a negative number if s is less than q. The positive number may not be 1.
In Java, class names are initially-capped. So LesserString2, not lesserString2.
It's always best to use meaningful names for your variables.
The reason you're not getting any output is #3.2 in the above list. You're getting a positive value, but not 1.
Here's a version with the issues above addressed:
import java.util.Scanner;
public class LesserString2 {
public static void main(String args[]) {
Scanner inputScanner = new Scanner(System.in);
int result;
String firstString;
String secondString;
firstString = inputScanner.nextLine();
secondString = inputScanner.nextLine();
result = firstString.compareTo(secondString);
if (result == 0) {
System.out.println("The strings are equal, please try again.");
} else if (result < 0) {
System.out.println("Lesser is: " + firstString);
} else { // No need for: if (result > 0) {
System.out.println("Lesser is: " + secondString);
}
}
}
Problem is in your condition.
you need to change if(result == 1) to if(result >0)
Here is the documenation of the return value. It does not only return -0, 0, 1
the value 0 if the argument string is equal to this string; a value less than 0 if this string is lexicographically less than the string argument; and a value greater than 0 if this string is lexicographically greater than the string argument.
If you would print the result you would notice that the result has the value of 2.
You need to change this else if(result == 1) part to else if(result > 0)
EDIT: also you need to swap the print of the Lesser value since you are allways writing the lexicographically higher value as the lesser value.
in the compareTo method, the result can be either
Less than 0, if compareTo sees that the instance is "lesser" than the parameter.
Bigger than 0, if compareTo sees that the instance is "greater" than the parameter. or
Equals to 0, if compareTo sees that the instance is equal.
So change
} else if(result == 1) {
to
} else if(result > 0) {
I am a beginner programmer. This is what I have so far. The directions for the question are kind of difficult. Here is what I am trying to accomplish..
You will write a program that converts binary numbers to base 10 numbers. This program will ask the user to enter a binary number. You will have to verify that what is entered by the user only has 0s and 1s. In the case the user entered letters, you have to keep asking the user for another input. When the input is valid, you will convert the binary number to a base 10 number. Please use the Question1.java file provided in the A2.zip file.
Valid input - In order to check if the input is valid your program should call the CheckInputCorrect method, which takes a String as an input parameter and returns a boolean value. An input string is considered valid if it corresponds to a number in binary representation.
More specifically, in the CheckInputCorrect method, you should scan this string to make sure it only contains ‘0’ or ‘1’ characters. As soon as you find a character that is not ‘0’ or ‘1’, the method should returns false. If the method reaches the end of the input string (i.e. all characters are ‘0’ or ‘1’) the method should return true.
Converter - At this point we assume that the input string is valid (checked with the CheckInputCorrect method). To convert the input from binary to base 10, you must implement the BinaryToNumber method. The BinaryToNumber method should take as parameter a String and return an integer, which corresponds to converted value in base 10.
The binary conversion should work as follows. For each digit in the binary number, if the digit is ‘1’ you should add the corresponding decimal value ( 20 for the rightmost digit, 21 for the next digits to the left, 22 for the next one, and so on) to a variable that will hold the final result to be returned. This can be easily accomplished by using a loop.
1) Am I on the right path?
2) I don't exactly know what I am doing and need you to help me figure that out....
Update1:
When I run this vvvv: It says "Please enter a binary number for me to convert: and then a place for me to type in my answer but whatever i put it just returns another box for me to type in but stops and doesn't evaluated anything.
import java.util.Scanner;
public class Question1
{
public static void main(String[] args)
{
System.out.println("Please enter a binary number for me to convert to decimal: ");
Scanner inputKeyboard = new Scanner(System.in);
String inputUser = inputKeyboard.nextLine();
boolean BinaryNumber = false;
String inputString = "";
while (!BinaryNumber){
inputString = inputKeyboard.next();
BinaryNumber = CheckInputCorrect(inputString);
System.out.println("You have given me a " + BinaryNumber + "string of binary numbers.");
}
int finalNumber = BinaryToNumber(inputString);
System.out.println("Congratulations, your binary number is " + finalNumber + ".");
}
public static boolean CheckInputCorrect(String input)
{
for (int i = 0; i < input.length(); i++)
{
while (i < input.length());
if (input.charAt(i) != '0' && input.charAt(i) != '1')
{return false;}
i++;
}
return true;
}
public static int BinaryToNumber(String numberInput)
{
int total = 0;
for (int i = 0; i < numberInput.length(); i++){
if (numberInput.charAt(i)=='1')
{
total += (int)Math.pow(2,numberInput.length() - 1 - i);
}
}
return total;
}
}
Original:
import java.util.Scanner;
public class Question1
{
public static void main(String[] args)
{
int binarynumber;
int arraySize = {0,1};
int[] binaryinput = new int[arraySize];
Scanner input = new Scanner(System.in);
System.out.println("Please enter a binary number");
binarynumber = in.nextInt();
if (binarynumber <0)
{
System.out.println("Error: Not a positive integer");
}
if (CheckInputCorrect) = true;
{
System.out.print(CheckInputCorrect);
}
public static boolean CheckInputCorrect(String input);
{
boolean b = true;
int x, y;
x = 0
y = 1
b = x || y
while (b >= 0 {
System.out.print("Please enter a binary number")
for (int i = 0; i < binarynumber.length; i++)
{
binaryinput[i] = in.nextInt();
if (binaryinput[i] = b.nextInt();
System.out.printl("Binary number is:" + binaryinput);
break outer;
if (binarynumber != b)
{
System.out.println("Error: Not a binary number")
}
return true;
}
}
public static int BinaryToNumber(String numberInput)
{
int remainder;
if (binarynumber <= 1) {
System.out.print(number);
return; // KICK OUT OF THE RECURSION
}
remainder = number %2;
printBinaryform(number >> 1);
System.out.print(remainder);
return 0;
}
}
}
As mentioned in my comments, your updated code contains two errors
while (i < input.length()); is an infinite loop, because it has no body. Therefore i cannot be increased and will stay lower than input.length().
inputString = inputKeyboard.next(); request another input after the first one and the first input will be ignored.
This is a fixed and commented version of your updated code:
public class Question1 {
public static void main(String[] args) {
System.out.println("Please enter a binary number for me to convert to decimal: ");
Scanner inputKeyboard = new Scanner(System.in);
String inputUser = inputKeyboard.nextLine();
//boolean BinaryNumber = false; // not needed anymore
//String inputString = ""; // not needed too
while (!checkInputCorrect(inputUser)) { // there is no reason for using a boolean var here .. directly use the returned value of this method
System.out.println("You have given me an invalid input. Please enter a binary number: "); // changed this message a little bit
inputUser = inputKeyboard.nextLine(); // re-use the "old" variable inputUser here
}
int finalNumber = binaryToNumber(inputUser);
System.out.println("Congratulations, your decimal number is " + finalNumber + ".");
}
public static boolean checkInputCorrect(String input) { // method names should start with a lower case letter
for (int i = 0; i < input.length(); i++) {
//while (i < input.length()); // this loop is deadly. Please think about why
if (input.charAt(i) != '0' && input.charAt(i) != '1') {
return false;
}
//i++; // what is the purpose of this? The "for" loop will increment "i" for you
}
return true;
}
public static int binaryToNumber(String numberInput) { //method name ... lower case letter ;)
int total = 0;
for (int i = 0; i < numberInput.length(); i++) {
if (numberInput.charAt(i) == '1') {
total += (int) Math.pow(2, numberInput.length() - 1 - i);
}
}
return total;
}
}