Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last year.
Improve this question
First day learning Java and I came across this problem: I need to divide 2 floats(given from command line input). I am getting an error every time I input my 2 floats. I included my code down below
import java.util.Scanner;
public class doubledivision
{
public static void main(String [] args)
{
float num1, num2;
Scanner in = new Scanner(System.in);
System.out.print("Please enter two floating point numbers: ");
num1 = in.nextInt();
num2 = in.nextInt();
float result = num1 / num2;
System.out.println(result);
}
}
If you want to read a number of type float from the user, you need to use :
in.nextFloat()
because this in.nextInt() will return a value of type int.
Also you need to consider some things :
You need to clear the scanner since you want 2 floating numbers , why ? because if the user enters :
>>> 1.0 2.0
The space will make your scanner assigne num1 with 1.0 and num2 with 2.0.
So if you want to ask the user 2 times use :
num1 = in.nextFloat();
in.nextLine(); // to refresh
num2 = in.nextFloat();
If the user enters zero (any number) divided by 0 will blow up​ your app , so add a check :
if(num2==0){
System.out.println("NaN");
}
else {
float result = num1 / num2;
System.out.println(result);
}
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am trying to pass user's input to the array through a scanner. The goal is to make the average value of the inputs, this is the code:
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
double[] str1 = new int [20] ;
str1 = scanner.next.Double();
System.out.println("Average is: " + Arrays.stream(str1).summaryStatistics().getAverage());
}
}
Below 2 statements are having syntax error and because of this code will not compile:
double[] str1 = new int [20] ;
str1 = scanner.next.Double();
you need to declare double array as double[] str1 = new double[20];
you need to take the double value as input like this scanner.nextDouble(); and as str1 is array we can't store the input directly as str1 = scanner.nextDouble(); in that case your program will give compile time error
Type mismatch: cannot convert from double to double[]
To resolve this error we need to store the value of every input at specific index like str1[0] = scanner.nextDouble();
Below is the working code as per your requirement(as I understand from your question):
Scanner scanner = new Scanner(System.in);
double[] str1 = new double[20] ;
for(int i = 0; i < 20;i++) {
str1[i] = scanner.nextDouble();
}
System.out.println("Average is: " + Arrays.stream(str1).summaryStatistics().getAverage());
I hope it will help you resolve the error you're facing.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I've got a strange issue (or at least strange to me). I've got a couple if-else-if statements that are causing strange behavior. For context, I'm essentially taking a char input using the Scanner class and using Scanner.nextInt().charAt(0). This appears to work fine if I check for the required characters and input a totally random character (it returns text to the terminal, breaks out, and exits). However, if I just hit enter at the char prompt, it creates what appears to be an infinite loop (maybe a memory leak?). Attached is the code I'm working on, as well as screenshots of it running in Coderunner2.
Thanks in advance!
import java.util.*;
import java.io.*;
public class phonebill
{
public static void main(String[] arg)
{
Scanner sc = new Scanner(System.in);
System.out.print("Please input the account number: ");
int acct = sc.nextInt(); // reads arbitrary account number
System.out.print("Please input service code: ");
char svc_code = sc.next().charAt(0); // reads service code
character
/* the following blocks check for the appropriate service codes.
* valid codes include p or P for 'Premium' service, and
* r or R for regular service. if no valid code is read,
* the program exits, informing the user to input a valid code.
*/
if (svc_code == 'p' || svc_code == 'P')
{
System.out.print("Please input daytime minutes: ");
int day_min = sc.nextInt();
System.out.print("Please input nighttime minutes: ");
int night_min = sc.nextInt();
System.out.println("Service code is " + svc_code + " and this condition works.");
}
else if (svc_code == 'r' || svc_code == 'R')
{
System.out.print("Please input used minutes: ");
int mins = sc.nextInt();
System.out.println("Service code is " + svc_code + " and this condition works.");
}
else
{
System.out.println("Please input a valid service code.");
}
System.out.print("That's all for now folks");
}
}
Code running normally
Code being weird
UPDATE: I'm just bad at Java and scanners.
It's not an infinite loop, or a memory leak.
It's just waiting for you to enter a non-empty string.
$ java phonebill
Please input the account number: 123
Please input service code:
string
Please input a valid service code.
That's all for now folks
(The blank lines are where I was just hitting enter. I eventually typed "string", and it stopped).
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
Please could someone take a look at my code. It won't compile because it says ; expected here - }elseif (convert == 2){.
I don't understand why, I'm pretty new to this.
Regards.
//user chooses what unit of measurments to convert, inputs number and displays conversion.
class Convertweight
{
public static void main (String [] args)
{
Scanner input = new Scanner(System.in);
//Declare variables
double feet=0.0, temp=0.0, weight=0.0, metres=0.0, f=0.0, stone=0.0, convert=0.0;
//choices of measurment to convert
System.out.println("Please choose and enter either 1,2 or 3 from the measurements below.");
System.out.println("1. Feet to metres");
System.out.println("2. C temp to F temp");
System.out.println("3. KG to stone");
convert=input.nextDouble();
//convert measurment if option 1 is chosen.
if (convert == 1) {
System.out.println("Enter measurement");
feet=input.nextDouble();
metres=feet/3.28;
System.out.println(metres + "m");
//convert temperature if option 2 is chosen.
} elseif (convert == 2){
System.out.println("Enter temperature in celsius");
temp=input.nextDouble();
F=C*1.8+32;
System.out.println(F + "f");
//convert weight if option 3 is chosen.
} elseif (convert == 3){
System.out.println("Enter weight in KG");
weight=input.nextDouble();
stone=weight/6.35029318;
System.out.println(stone+"st");
}
else if is the correct format elseif will cause a compilation error. check the documentation for better understanding.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm pretty new to Java so please forgive my noob question.
How can I make the error checking logic syntactically correct and what built in methods might I use?
public static void initialize(HighScores[] scores) {
Scanner input = new Scanner(System.in);
// capture input
for (int i = 0; i < 5; i++) {
System.out.println("Enter the name for score #" + i + ": ");
String name = input.next(); // Alex
System.out.println();
System.out.println("Enter the score for score #" + i + ": ");
int score = input.nextInt();
// Error checking
// if the 'input' is NOT of type 'int'
if (score.getClass().getSimpleName() != int) {
// Ask to input a numeric value
System.out.println("Please enter a numeric value! :)");
score = input.nextInt(); // inputting a value in again
}
System.out.println();
HighScores object = new HighScores(name, score);
scores[i] = object;
}
}
What it would look like if correct:
Enter the name for score #0:
Alex
Enter the score for score #0:
s
Please enter a numeric value! :)
5
Enter the name for score #0:
John
Enter the score for score #0:
3
.... etc...
You seem to be confused,
try {
int score = input.nextInt();
} catch (InputMismatchException ime) {
ime.printStackTrace();
}
Will always be of type int (or you'll get an Exception), per the Scanner#nextInt()
Scans the next token of the input as an int.
and note that the throws says
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
It is also possible to call Scanner#hasNextInt() first,
if (input.hasNextInt()) {
int score = input.nextInt();
} else {
System.out.println(input.next() + " isn't an int");
}
First, as guys already mentioned in their comments you do not need this. If your variable is defined as int it is int and you do not have to check this.
Second, int is a primitive, so you cannot say score.getClass().
However in some cases (if you write some generic code that must care about several, yet certain types) you probably want to fix your if statement as following:
Integer score = .....
.........
if (Integer.class.equals(score.getClass())) {
// your code here
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am a beginner,I'm having problem with my very first code.I just trying to solve coupling shaft alignment.
It says, "illegal start of expression".Can someone help me with this problem? thanks
Here's my code:
import java.util.Scanner;
public class Front {
public static void main(String []args){
Scanner input = new Scanner(System.in);
Double A = input.nextDouble();
Double B = input.nextDouble();
Double C = input.nextDouble();
Double S = input.nextDouble();
Double M = input.nextDouble();
Double F = B / A * (S-M)/2 - S/2;
System.out.println("The front foot is: " + F +);
}
}
You missed an operand after your last + in System.out.println("The front foot is: " + F +);
Another option is to use formatted output:
System.out.printf("The front foot is: %f\n", F.floatValue());