This program should count amount of digits in a number.
Here is my code:
import java.util.Scanner;
public class Converter {
public static void main(String[] args) {
Scanner marty = new Scanner(System.in);
float sk;
System.out.println("Enter start number: ");
sk = marty.nextFloat();
int numb = (int)Math.log10(sk)+1;
System.out.println(numb);
marty.close();
}
}
I am getting this kind of error, while tryin to input number with 4 or more digits before comma, like 11111,456:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextFloat(Unknown Source)
at Converter.main(Converter.java:11)
Any ideas about what the problem may be?
Taking the log (base10) of a number and adding 1 is not going to give you the correct answer for the number of digits of the input number anyway.
Your given example of 11111.465 has 8 digits. The log10 of this number is 4.045... adding 1 gives you the answer of 5.
Another example: 99, Log10(99) = 1.99, cast as int = 2, add 1 = 3... clearly is only 2 digits.
You could just read the input as a String then do something like the following instead
int count = 0;
String s = /* (Input Number) */
for(char c : s.toCharArray())
{
if(Character.isDigit(c))
count++;
}
You would have to also have to check it is actually a number though by checking its pattern...
When inputting a number, you aren't supposed to include commas unless you expect to split it. If you want a decimal, use a "." instead. If you want a number greater than 999, don't include a comma
Like many people have said, the comma is messing you up.
One option you may consider if your input needs comma is replacing the commas from the input string before try to count the number of digits.
System.out.println("Enter start number: ");
String input = marty.nextLine();
float sk = Float.parseFloat(input.replace(",", ".")); // use input.replace(",", "") if you want to remove commas
int numb = (int)Math.log10(sk)+1;
System.out.println(numb);
Related
How can I check if the next three input user is giving is an int value,
like let's say there is three variables,
var1
var2
var3
And I am taking input as,
Scanner sc = new Scanner (System.in);
var1 = sc.nextInt();
var2 = sc.nextInt();
var3 = sc.nextInt();
Now if I want to use while(sc.hasNextInt()) to determine if the next input is an int or not then it will only check if the next input for var1 is int or not and won't check for the other to variables, var2, var3. One thing can be done by using while loop with if (condition). For example,
Scanner sc = new Scanner (System.in);
while (sc.hasNextInt()) {
var1 = sc.nextInt();
if (sc.hasNextInt()) {
var2 = sc.nextInt();
if (sc.hasNextInt()) {
var3 = sc.nextInt();
}
}
}
But this looks lengthy and needs a lot to write. For similar issue I have seen for Language C there is a method for scanf() which can do the trick. For example,
while(scanf("%d %d %d", &var1, &var2 & var3) == 3) {
// Statements here
}
So my question is there any such features available in java's Scanner.hasNextInt or Scanner.hasNext("regex").
I have also tried sc.hasNext("[0-9]* [0-9]* [0-9]*") but didn't worked actually.
Thank you in advance.
hasNext(regex) tests only single token. Problem is that default delimiter is one-or-more-whitespaces so number number number can't be single token (delimiter - space - can't be part of it). So sc.hasNext("[0-9]* [0-9]* [0-9]*") each time will end up testing only single number. BTW in your pattern * should probably be + since each number should have at least one digit.
To let spaces be part of token we need to remove them from delimiter pattern. In other words we need to replace delimiter pattern with one which represents only line separators like \R (more info). This way if user will write data in one line (will use enter only after third number) that line would be seen as single token and can be tested by regex.
Later you will need to set delimiter back to one-or-more-whitespaces (\s+) because nextInt also works based on single token, so without it we would end up with trying to parse string like "1 2 3".
Scanner sc = new Scanner(System.in);
sc.useDelimiter("\\R");
System.out.print("Write 3 numbers (sepate them with space): ");
while(!sc.hasNext("\\d+ \\d+ \\d+")){
String line = sc.nextLine();//IMPORTANT! Consume incorrect values
System.out.println("This are not 3 numbers: "+line);
System.out.print("Try again: ");
}
//here we are sure that there are 3 numbers
sc.useDelimiter("\\s+");//nextInt can't properly parse "num num num", we need to set whitespaces as delimiter
int var1 = sc.nextInt();
int var2 = sc.nextInt();
int var3 = sc.nextInt();
System.out.println("var1=" + var1);
System.out.println("var2=" + var2);
System.out.println("var3=" + var3);
Possible problem with this solution is fact that \d+ will let user provide number of any length, which may be out of int range. If you want to accept only int take a look at Regex for a valid 32-bit signed integer. You can also use nextLong instead, since long has larger range, but still it has max value. To accept any integer, regardless of its length you can use nextBigInteger().
I tried with nextLine method and usage of Pattern. Regex is matching with 3 numbers which is separeted with space. So it can be like this i think ;
Scanner scanner = new Scanner(System.in);
Pattern p = Pattern.compile("[0-9]+\\s[0-9]+\\s[0-9]+$");
while(!p.matcher(scanner.nextLine()).find()){
System.out.println("Please write a 3 numbers which is separete with space");
}
System.out.println("Yes i got 3 numbers!");
I hope this helps you.
I'm doing a project for a Uni course where I need to read an input of an int followed by a '+' in the form of (for example) "2+".
However when using nextInt() it throws an InputMismatchException
What are the workarounds for this as I only want to store the int, but the "user", inputs an int followed by the char '+'?
I've already tried a lot of stuff including parseInt and valueOf but none seemed to work.
Should I just do it manually and analyze char by char?
Thanks in advance for your help.
Edit: just to clear it up. All the user will input is and Int followed by a + after. The theme of the project is to do something in the theme of a Netflix program. This parameter will be used as the age rating for a movie. However, I don't want to store the entire string in the movie as it would make things harder to check if a user is eligible or not to watch a certain movie.
UPDATE: Managed to make the substring into parseInt to work
String x = in.nextLine();
x = x.substring(0, x.length()-1);
int i = Integer.parseInt(x);
Thanks for your help :)
Try out Scanner#useDelimiter():
try(Scanner sc=new Scanner(System.in)){
sc.useDelimiter("\\D"); /* use non-digit as separator */
while(sc.hasNextInt()){
System.out.println(sc.nextInt());
}
}
Input: 2+33-599
Output:
2
33
599
OR with your current code x = x.substring(0, x.length()-1); to make it more precise try instead: x = x.replaceAll("\\D","");
Yes you should manually do it. The methods that are there will throw a parse exception. Also do you want to remove all non digit characters or just plus signs? For example if someone inputs "2 plus 5 equals 7" do you want to get 257 or throw an error? You should define strict rules.
You can do something like: Integer.parseInt(stringValue.replaceAll("[^\d]","")); to remove all characters that are no digits.
Hard way is the only way!
from my Git repo line 290.
Also useful Javadoc RegEx
It takes in an input String and extracts all numbers from it then you tokenize the string with .replaceAll() and read the tokens.
int inputLimit = 1;
Scanner scan = new Scanner(System.in);
try{
userInput = scan.nextLine();
tokens = userInput.replaceAll("[^0-9]", "");
//get integers from String input
if(!tokens.equals("")){
for(int i = 0; i < tokens.length() && i < inputLimit; ++i){
String token = "" + tokens.charAt(i);
int index = Integer.parseInt(token);
if(0 == index){
return;
}
cardIndexes.add(index);
}
}else{
System.out.println("Please enter integers 0 to 9.");
System.out.print(">");
}
Possible solutions already have been given, Here is one more.
Scanner sc = new Scanner(System.in);
String numberWithPlusSign = sc.next();
String onlyNumber = numberWithPlusSign.substring(0, numberWithPlusSign.indexOf('+'));
int number = Integer.parseInt(onlyNumber);
I am suppose to write a program that accepts an integer from the user using the Scanner class and displays the char data type representation of it. Assume the user will only enter a number from 0 to 127. As of now I have this.
import java.util.Scanner;
public class ASCIICharacterMcAfooseMark {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
//This should allow the user to enter a number
System.out.print("Enter a number:");
String str = input.nextLine();
System.out.println(input);
//Need to get this to allow the entered number to show char value
int num = 0 - 127;
char c;
c = (char)num;
System.out.println(c);
}
}
When I enter this into command prompt it lets me enter a number, but all I get is a bunch of words and then a question mark. Any help would be appreciated. I am using Notepadd++ in Java.
Edit: For 32, the char representation would be space.
Edit: For the System.out.println(input); I was going by what I saw in my teacher's powerpoint. Should I get rid of it?
What do you mean by "char data type representation"? Given an input of
32 (for example), what would be the correct "char data representation"
to display in this case?
When I enter this into command prompt it lets me enter a number, but
all I get is a bunch of words and then a question mark.
Not all ints map to plain text chars. Some of them map to spaces, some to backspaces, some to "print line feeds", some to "modem control characters". For starters, look to positions 0-127 in the ACII table; however, Java really uses Unicode, so look to Unicode if you want to know how things happen above 127 (which includes your negative numbers).
Also, keep in mind that if you do not have a fully populated "glyph set" (the part of the font that draws to the screen, then various "code points" (the numbers that correspond to the glyphs) can't be drawn. Typically this is resolved by many systems with a substitution glyph, which is that funky question mark you're seeing.
Change your line:
int num = 0 - 127;//your num will always hold -127
To
int num = Integer.parseInt(str);//so you get integer representation of number string you just entered.
Notes apart:
Perhaps here System.out.println(input); you are trying to print string user entered, so you might need to change it to System.out.println(str);
There is an api which is specifically to read int from scanner and may be worth looking at here
Let's have a look at what your program is doing.
Scanner input = new Scanner(System.in);
Note that input is a Scanner object.
System.out.println(input);
Here you are displaying the Scanner object itself. Not what the user entered, because that is in the variable str. Maybe you wanted to do this instead:
System.out.println(str);
Then this line:
int num = 0 - 127;
This just sets num to -127. What you wanted to do instead is parse whatever is in str into an int:
int num = Integer.parseInt(str);
if you're assuming the user will put a number from 0 to 127, then try it like this:
import java.util.Scanner;
public class ASCIICharacterMcAfooseMark {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number:");
String str = input.nextLine();
System.out.println(input);
int num = Integer.parseInt(str); //you weren't using the value from the input
char c;
c = (char)num;
System.out.println(c);
}
}
char c;
Scanner input = new Scanner(System.in);
System.out.print("Enter a number:");
int ip = input.nextInt();//<---- get integer
c = (char)ip;// cast int value to char
System.out.println(c);
if input is 97 output will be a
I made a method within a class that is supposed to parse a file with the format: name, xxx-xxx-xxxx
for every line. I'm trying to grab the phone number and put every digit into an array of ints and return that array. Here is my code.
This is the line that causes the error---
theIntNumber=Integer.parseInt(justAnotherString);
If I had: Nicholas James, 912-345-6789
then....
justAnotherString = "9123456789" and it throws an error when trying to parse that string for an int. I'm confused as to why this is happening, shouldn't it parse the int from this string?
Thank you for any answers.
public int[] getPhoneNumberArray() throws FileNotFoundException
{
Scanner scan = new Scanner(file);
while(scan.hasNextLine())
{
String thePhoneNumber = "";
String justAnotherString = "";
int theIntNumber=0;
String line = scan.nextLine();
Scanner parser = new Scanner(line);
parser.useDelimiter(",");
parser.next();
parser.useDelimiter(" ");
parser.next();
thePhoneNumber = parser.next();
Scanner lol = new Scanner(thePhoneNumber);
lol.useDelimiter("-");
justAnotherString += lol.next();
justAnotherString += lol.next();
justAnotherString += lol.next();
theIntNumber=Integer.parseInt(justAnotherString);
for(int i=10;i>0;i--)
{
phoneNumberArray[i-1]=theIntNumber%10;
}
}
for(int a=0;a<10;a++)
{
System.out.println("Phone Number: ");
}
return phoneNumberArray;
}
EDIT: Previous number was 123-456-7890. The number I had before was larger than the 2.1 billion that java can handle. 987-654-3210 is a better example.
This is the error I'm getting.
Exception in thread "main" java.lang.NumberFormatException: For input string: "9876543210"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at exam2.Contact.getPhoneNumberArray(Contact.java:71)
at exam2.ExamTwoInput.main(ExamTwoInput.java:83)
Your code is working here, the only issue I see is that your formula for converting the digits of the int number to an array appears flawed. You don't need the int anyway, since you have it as justAnotherString. Basically, you could use Character.digit(char, int) like -
int[] phoneNumberArray = new int[justAnotherString.length()];
for (int i = 0; i < justAnotherString.length(); i++) {
phoneNumberArray[i] = Character.digit(justAnotherString.charAt(i), 10);
}
System.out.println(Arrays.toString(phoneNumberArray));
Of course, you could also parse the telephone number with something like
String line = "Nicholas James, 123-456-7890";
// get everything after the last space.
String phone = line.substring(line.lastIndexOf(' ') + 1);
phone = phone.replace("-", ""); // remove the '-' symbols
int[] phoneNumberArray = new int[phone.length()];
for (int i = 0; i < phone.length(); i++) {
phoneNumberArray[i] = Character.digit(phone.charAt(i), 10);
}
System.out.println(Arrays.toString(phoneNumberArray));
which has the advantage that it will work with (and without) dashes.
As an aside, you can't store a telephone number in an integer. It loses both leading zeroes, and the plus sign.
For instance, imagine you were given the number for the British Prime Minister, +44 20 7925 0918. The plus sign there indicates that the call is an international call. It would be replaced by 011 in the North American Numbering Plan, or by 00 in the European Telephony Numbering Space. How would you represent that telephone number as an int?
I know this question is so old, but till now not have accepted answer.
as your note:
EDIT: Previous number was 123-456-7890. The number I had before was larger than the 2.1 billion that java can handle. 987-654-3210 is a better example.
so, please use Long.valueOf(str) instead of Integer.parseInt(str) or Integer.valueOf(str)
hope this help u all :)
This initial part is just supposed to take a mixed fraction like 1 1/2 and convert it to 3/2
What I have is below, the problem is that when I run it it gives me an error. said error is
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(Unknown Source)
at Calculator.main(Calculator.java:18)
Code begins below:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
// prompt user for fraction string
// receive and store in variable
// convert to improper fraction
//print
System.out.println("Enter a fraction:"); //prompt for string
Scanner input = new Scanner(System.in); //Receive
String fractionAsString = input.next(); //store in variable
int getSpace = fractionAsString.indexOf('_'); //should fine where java spaces for the initial entering of fractoin
int getSlash = fractionAsString.indexOf('/'); //should find divisor (like in 1 1/2)
String firstString= fractionAsString.substring(0, getSpace+1);//converting string to int
String secondString=fractionAsString.substring(getSpace, getSlash);
String thirdString=fractionAsString.substring(getSlash+1);
int wholeNumber=Integer.parseInt(firstString);
int numerator=Integer.parseInt(secondString);
int denominator=Integer.parseInt(thirdString);
int newResult=wholeNumber*denominator;
int finalResult=numerator+newResult;
System.out.println(finalResult+"/"+denominator);
input.close();
}
}
The problem is input.next(). Since you need the whole string which the user entered you should use nextLine() not next().
Reason:
next() takes space as the default delimiter.
nextLine() takes return as the default delimiter.
Be warned there are other problems in your code. You may want to print variables to know what is stored in them.
Happy Learning!
In your code, next() takes space as the default delimiter, Use nextLine() as it takes return as the default delimiter. By the way use some custom operator like underscore(_) to represent whole-number instead of using space. And split the string to get wholeNumber, numerator and denominator.