Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm trying to read some data from a user and do some very simple calculations with them, but for some reason I can't explain, the program stops after first 2-3 inputs (given they are doubles). Can someone explain this behaviour?
My code:
Scanner in = new Scanner(System.in);
System.out.println("Enter your values, 'q' to quit: ");
double average, input, smallest, largest, range;
average = smallest = largest = range = Double.parseDouble(in.nextLine());
int counter = 1;
while (in.hasNextDouble()) {
input = Double.parseDouble(in.nextLine());
smallest = input < smallest ? input: 0;
largest = input > largest ? input: 0;
average += input;
counter++;
}
Consider this input:
1.23
4.56 7.89
To Scanner this looks like a valid sequence of three doubles on two separate lines. When you call nextLine to obtain the first double, it works fine, because the number occupies the entire string.
When you do the same for the next double, the string that you try to parse looks like this:
"4.56 7.89"
This string is not a valid double, so you cannot parse it.
One approach to deal with this problem is to call nextDouble, and avoid parsing altogether. Pairing up hasNextDouble() with nextDouble() has an advantage of not requiring users to put their data on different lines.
Note: The first call to Double.parseDouble(in.nextLine()) happens without checking that Scanner has next double, so your program could crash on initial bad input.
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
I'm doing the Java MOOC by Helsinki University. Stuck on the following problem:
Write a program which prints the integers from 1 to a number given by the user.
Sample output
Where to? 3
1
2
3
The code below outputs the expected results but is not accepted as valid. Any suggestions or pointers are welcome, thank you!
import java.util.Scanner;
public class FromWhereToWhere {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Write your program here
System.out.println("Where to?");
int userInput = Integer.valueOf(scanner.nextLine());
int start = 1;
while (start <= userInput) {
System.out.println(start);
start++;
}
}
}
Most likely the system that tests your program is stuffing values into standard input (System.in) with spaces, and assumes that you will read with .nextInt().
If that's not it, double check the program description; what is supposed to happen if I enter -1? 0? 1985985410395831490583440958230598? FOOBAR?
If it doesn't say, then presumably the verifier won't throw those inputs at you (if it does, file a bug with the MOOC provider, the course itself needs fixing if that is the case), but if it does, you're going to have to code those rules in, probably.
This shouldn't be it, but to exactly mirror the desired result, it's System.out.print("Where to? "); - note, no ln, and a trailing space.
You did not check if the user input is valid, I would suggest starting off with the following:
check if userInput is a valid number (includes numeric characters).
check if userInput is larger or equal to 1.
your answer is ok but can be optimized to the beginners levels if that is what your teacher is expecting because:
you can get an int directly from scanner, no need to use the wrapper class Integer.
you can use another loop ... a for loop
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Write your program here
System.out.println("Where to?");
int userInput = scanner.nextInt();
System.out.println("ok!");
for (int i = 1; i <= userInput; i++)
{
System.out.println(i);
}
}
Just try by Removing
System.out.println("Where to?");
with
System.out.print("Where to?");
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm trying to make a ISBN checker but it's not working. An example would be the user inputs 013601267 and return 0136012671. I'm not understanding what the problem is. No loops.
Any help would be great.
import java.util.*;
public class ISBN{
public static void main(String[]args){
Scanner in=new Scanner(System.in);
System.out.print("Enter 9 digit ISBN");
//variables//
int d1=in.nextInt();
int d2=in.nextInt();
int d3=in.nextInt();
int d4=in.nextInt();
int d5=in.nextInt();
int d6=in.nextInt();
int d7=in.nextInt();
int d8=in.nextInt();
int d9=in.nextInt();
int d10=(d1*1+d2*2+d3*3+d4*4+d5*5+d6*6+d7*7+d8*8+d9*9) %11;
//keyboard
if (d10==10){
System.out.print("ISBN"+d1+d2+d3+d4+d5+d6+d7+d8+d9+"X");}
else if(d10 !=10); {
System.out.print("ISBN"+d10);}
}
}
When someone enters their ISBN, are they entering it with spaces in between?
nextInt() will retrieve the integers separated by spaces, so it is likely that d1 is receiving the entire nine integers.
If you are entering them one at a time, then it should work.
Either enter the digits with spaces in between them, or each on their own line. Scanner will take care of the rest.
Note:
If you don't want the user to have to enter the digits one-by-one, try taking their input as:
String digits = in.nextLine();
You can reference each digit in that string with digits.charAt(0) etc.
int d1=Integer.parseInt("" + digits.charAt(0));
and so on. This will convert the single character digits.charAt(0) to your integer for the formula.
Hope this helps!
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I was required to make a code that accepted a binary number (1's and 0's) and then counted how many ones were in that binary number. My code fulfills this purpose.
The second part of the exercise is this: if the user enters a number that is NOT binary, I must output that there is an error and keep prompting the user until they give a binary number.
Can someone show me how to incorporate this? I have tried several times but cannot make it click. Thanks! Here is my code.
import java.util.Scanner;
public class NewClass
{
public static void main( String [] args )
{
Scanner scan = new Scanner( System.in);
int i = 0, count = 0;
String number;
System.out.println("Please enter a binary number.");
number = scan.next();
String number1 = "1";
while ((i = number.indexOf(number1, i++)) != -1) {
count++;
i += number1.length();
}
System.out.println("There are "+ count + " ones in the binary number.");
}
}
You already know how to find all of the 1's; you should be able to do something similar to find all of the 0's.
If the sum of those two counts is not the length of the string, there must be at least one illegal character in it.
If you use the parseInt method you can do
Integer.parseInt("1100110", 2) returns 102
or in your case
int intVal = Integer.parseInt(number, 2);
as per the javadocs
Throws:
NumberFormatException - if the String does not contain a parsable int.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
In my application user can enter number between 0 to 999
However, whether he enter "0" or "00" or "000" should understood and treated differently.
All the functions that in know convert the input into single zero "0" before putting it into the variable.
private static void AddAmountChart1D (){
String str_pana;
int int_pana, Amount;
Scanner UserInput = new Scanner(System.in);
System.out.print("Enter the game pana : ");
str_pana = UserInput.nextLine(); /* This line should treat "0", "00" & "000" as different types of strings.
Presently it make all three as "0"
System.out.print("Enter the Amount : ");
Amount = UserInput.nextInt();
int_pana = get_int_pana(str_pana);
ChartAmount1D[int_pana] = ChartAmount1D[int_pana]+Amount;
}
Your purpose is not that much clear to me.
But if you use
UserInput.nextLine();
this will be treated as a String so it'll return the zeros like "0", "00" or "000".
Further if you want the value to be processed as a number simply use
int number = Integer.parseInt(str_pana);
and use the number.
Edit
Please try this and check the results for "0", "00" or "000".
if (str_pana.equals("0")) {
System.out.println("Zero");
}else if (str_pana.equals("00")) {
System.out.println("Zero-Zero");
}else if (str_pana.equals("000")) {
System.out.println("Zero-Zero-Zero");
}
Actually my point is to check the zeroes so that you can set the integer values in the if clause and convert them to respective integer values to be used later.
Read whole line.
Use function
public boolean startsWith("0")
From String class
If it doesn't return true - just parse.
Else count zeros
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How to fill an array of integers in Java by asking the user to enter the number once ?
for example :
Enter 3 integers >: 123
then I want to get the array filled like that :
arr[0]=1
arr[1]=2
arr[2]=3
I hope the question is clear :)
rgds
One way of going about this would be to take the integer in as a String. You can then use toCharArray() in order to grab an array of the characters - these characters can then be individually parsed into Integer by utilizing Character.getNumericValue().
See the String and Character APIs for more details on those methods.
Small example of what I mean:
String numbers = "123";
char[] numArray = numbers.toCharArray();
for (char c : numArray) {
int num = Character.getNumericValue(c);
// Do what you will with the number.
}
As noted, this particular implementation would only work in this format if you are assuming that each integer is single digit.
How about this:-
Scanner input = new Scanner(System.in);
System.out.println("How many numbers do you want to enter?");
int num = input.nextInt();
int array[] = new int[num];
System.out.println("Enter the " + num + " numbers now.");
for (int i = 0 ; i < array.length; i++ ) {
array[i] = input.nextInt();
}