This is my first program in java and I haven't found any good websites like this one for C++ and it's confusing for me because I just started writing java and I just came from C++. Anyways, concerning this code, could someone explain how to fix this code because of the line containing Scanner and/or how to simply receive inputs, because I haven't found any simple way to translate cin >> from C++
public class input {
public static void main(String[] args) {
double total = 0;
Scanner in = new Scanner(System.in);
System.out.println("As you enter numbers, they will be added.");
System.out.println("Entering a non-number will stop the program.");
while (in.hasNextDouble()) {
double n = in.nextDouble();
total = total + n;
System.out.println("The total is " + total);
}
}
}
Your code works. Just make sure you have import java.util.Scanner. On a related note, use Eclipse or Netbeans as they would have told you this. Also, you should capitalize class names and put your class in a package instead of in the "default package". I recommend "Head First Java".
package sand1;
import java.util.Scanner;
public class Input {
public static void main(String[] args) {
double total = 0;
Scanner in = new Scanner(System.in);
System.out.println("As you enter numbers, they will be added.");
System.out.println("Entering a non-number will stop the program.");
while (in.hasNextDouble()) {
double n = in.nextDouble();
total = total + n;
System.out.println("The total is " + total);
}
}
}
Here is output when I ran it. I think I might consider it a bug that I was able to hit enter with a blank line without it ending.
run:
As you enter numbers, they will be added.
Entering a non-number will stop the program.
12.2
The total is 12.2
43
The total is 55.2
a
BUILD SUCCESSFUL (total time: 11 seconds)
I'm at work and don't have the jdk installed, so I can't compile and run this. Giving a quick look though, it seems like the only thing you might have problem breaking out of the scanner, though. After entering a few numbers, try pressing ctrl-d - this should signal end of input.
As Borealid said you need to add the following line at the top of the class to get it to compile:
import java.util.Scanner;
Also note that by convention in java classes are named with an uppercase character Input, not input.
Finally, you can obtain input directly through System.in.read() and the other overloaded permutations of the read() method, against System.in
Check out the Java Tutorials,they're quite good for a beginner
Related
I am very new to Java but am working through the book Java: How to program (9th ed.) and have reached an example where for the life of me I cannot figure out what the problem is.
Here is a (slightly) augmented version of the source code example in the textbook:
import java.util.Scanner;
public class Addition {
public static void main(String[] args) {
// creates a scanner to obtain input from a command window
Scanner input = new Scanner(System.in);
int number1; // first number to add
int number2; // second number to add
int sum; // sum of 1 & 2
System.out.print("Enter First Integer: "); // prompt
number1 = input.nextInt(); // reads first number inputted by user
System.out.print("Enter Second Integer: "); // prompt 2
number2 = input.nextInt(); // reads second number from user
sum = number1 + number2; // addition takes place, then stores the total of the two numbers in sum
System.out.printf( "Sum is %d\n", sum ); // displays the sum on screen
} // end method main
} // end class Addition
I am getting the 'NoSuchElementException' error:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:838)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at Addition.main(Addition.java:16)
Enter First Integer:
I understand that this is probably due to something in the source code that is incompatible with the Scanner class from java.util, but I really can't get any further than this in terms of deducing what the problem is.
NoSuchElementException Thrown by the nextElement method of an Enumeration to indicate that there are no more elements in the enumeration.
http://docs.oracle.com/javase/7/docs/api/java/util/NoSuchElementException.html
How about this :
if(input.hasNextInt() )
number1 = input.nextInt(); // if there is another number
else
number1 = 0; // nothing added in the input
You should use hasNextInt() before assigning value to variable.
NoSuchElementException will be thrown if no more tokens are available. This is caused by invoking nextInt() without checking if there's any integer available. To prevent it from happening, you may consider using hasNextInt() to check if any more tokens are available.
I faced this Error with nextDouble(), when I input numbers such as 5.3, 23.8 ... I think that was from my PC depending on computer settings that use Arabic (23,33 instead 23.33), I fixed it with add:
Scanner scanner = new Scanner(System.in).useLocale(Locale.US);
You must add input.close() at the end...
This error is mostly occur in case of 0nline IDE's on which you are testing your code. It is not configured properly, as if you run the same code on any other IDE/Notepad it works properly because the online IDE is not designed such a way that it will adjust the input code of your format, So you have to take input as the Online IDE supports.
If I may, I solved this issue today by realizing that I had multiple functions that used an instance of a Scanner, each. So basically, try refactoring so that you have only one instance opened and then closed in the end - this should work.
For anyone using gradle's application plugin, you must wire it to the standard console in build.gradle(.kts) otherwise it will keep throwing the NoSuchElementException error if you try to use scanner.
For groovy:
run {
standardInput = System.in}
For gradle kotlin dsl:
tasks.withType<JavaExec>() {
standardInput = System.`in`}
Integer#nextInt throws NoSuchElementException - if input is exhausted
You should check if there is a next line with Integer#hasNextLine
if(sc.hasNextLine()){
number1=sc.nextInt();
}
I added a single static scanner (sc) at the top of my class and closed it (sc.close()) when coming out of the whole class wherever I used return statements. Again that's one instance of scanner as suggested by another answer, which should be static.
package com.example.com;
import java.util.Scanner;
public class someClass {
static Scanner sc = new Scanner(System.in);
//Whole world of methods using same sc.
//sc.close()); return;
}
Other than that you can add #SuppressWarnings("resource") on the top of the troubling method to make the warning go away. But be careful about resource leaks.
I have just started my 2nd programming course at college and our first assignment is rather simple, intended to basically check our environment and to check we know how to submit assignments through the course website.
When I run the code we have been supplied with, it hangs where it is supposed to prompt for the user to enter a number, so that it can print it. I inserted a series of println statements to determine where it was hanging.
It prints TEST1, TEST2 and TEST3, but never makes it to TEST4. So there must be something wrong with the line:
number = input.nextInt();
But I can't for the life of me see what's wrong with that line. Any help would be greatly appreciated! :)
Anyway, here is the code
package rossassignment1;
import java.util.Scanner; // use the Scanner class located in the "java.util" directory
public class RossAssignment1 {
public static void main (String[] args) {
System.out.println("TEST 1");
int number;
System.out.println("TEST 2");
Scanner input = new Scanner(System.in);
System.out.println("TEST 3");
number = input.nextInt();
System.out.println("TEST 4"); // display the number with other messages
System.out.print("This program reads an integer from a keyboard,\n"
+ " and print it out on the display screen.\n"
+ "The number is: " + number + ".\n"
+ "make sure that you get the exact same output as the expected one!\n");
}
}
After the line input.nextInt() is run the program is waiting for the user (you, or whatever marking system is being used) to input an integer in the console. After you do so the program will continue to your TEST4 line.
If after entering an integer, the codes after that still don't show up, you can do this:
number = input.nextInt();
input.nextLine(); //Add this
It will clear the newline.
Alternatively, I prefer to do this:
number = Integer.parseInt(input.nextLine());
The following requisites are those for the program I'm currently having an issue with:
The program must be able to open any text file specified by the user, and analyze the frequency of verbal ticks in the text. Since there are many different kinds of verbal ticks (such as "like", "uh", "um", "you know", etc) the program must ask the user what ticks to look for. A user can enter multiple ticks, separated by commas.
The program should output:
the total number of tics found in the text
the density of tics (proportion of all words in the text that are tics)
the frequency of each of the verbal tics
the percentage that each tic represents out of all the total number of tics
My program is working very well, but what I basically need to do is that I must use separate methods for each component of the analysis. So I think the idea is that I need to split up the program in a few parts, which I have done by using the comments // because I'm basically having problems determining which type I should return, I know the last part (// public static void output(){)
should definitely be void because it returns nothing and only prints out.
public static void main(String[] args) throws FileNotFoundException {
double totalwords = 0; // double so density (totalwords/totalticks) returned can be double
int totalticks = 0;
System.out.println("What file would you like to open?");
Scanner sc = new Scanner(System.in);
String files = sc.nextLine();
Scanner input = new Scanner(new File(files));
// public static int[] initialise()
System.out.println("What words would you like to search for? (please separate with a comma)");
String ticks = sc.nextLine();
ticks = ticks.toLowerCase();
String[] keys = ticks.split(",");
int[] values = new int[keys.length];
// public static int[] processing(){?
for (int z=0; z<keys.length; z++){
values[z] = 0;
}
while (input.hasNext()){
String next = input.next();
totalwords++;
for (int x = 0; x<keys.length; x++){
if (next.toLowerCase().equals(keys[x])){
values[x]+=1;
}
}
}
for (Integer u : values) {
totalticks += u;
}
//public static void output(){
System.out.println("Total number of tics :"+totalticks);
System.out.printf("Density of tics (in percent): %.2f \n", ((totalticks/totalwords)*100));
System.out.println(".........Tick Breakdown.......");
for (int z = 0; z<keys.length; z++){
System.out.println(keys[z] + " / "+ values[z]+" occurences /" + (values[z]*100/totalticks) + "% of all tics");
}
}
Essentially the problem I'm having is the scope of the variables because Eclipse (my IDE) no longer recognizes the variables within each method once I get them out of comments - I know I need to use some static variables but would really like a hand as to how I could hook my program up together using methods.
Thanks a bunch,
M
You should do an object (class) decomposition. First ask the question "What objects do I have". (At a quick glance you might have "Text" and "Ticks" objects. You then want to see what methods you want to use for each object. For example in Text have countTicks(Ticks). Conotinue in this fashion to decompose your program.
First, please indent your code more consistently, with the first line of a block three spaces farther to the right, such as
for(...) {
//Do stuff
if(...) {
//Do stuff
}
}
It is hard to read what you've posted (luckily someone spruced it up for you!).
Consider re-writing your program from scratch, instead of trying to fix what you already have. Your current knowledge of the problem should allow you to recreate it pretty quickly. You will probably be able to cut and paste bits and pieces from your original code as well.
How about starting small, with something like
Scanner sc = getInputScannerFromUserInput();
private static final Scanner getInputScannerFromUserInput() {
System.out.println("What file would you like to open?");
return new Scanner(System.in);
}
and just go from there. Bit by bit. Good luck!
I am very new to Java, (and to programming altogether). I am sure that the solution to my problem is very simple, but I just can't figure it out. The code below is a small chunk of my program. But it is still compile-able, and still has the same problem.
Here is the code::
import java.util.Scanner;
public class Practice{
public static void main(String args[]){
Scanner input = new Scanner(System.in);
String command = "";
double d; // Distance
double t; // Time
double s; // Speed
System.out.println("Hello, I am the Physics Calculator!!");
while (!command.equals("end")){
System.out.print("What would you like to calculate?: "); // after the first loop, this statement is printed twice to the screen! :(
command = input.nextLine();
System.out.println();
if (command.equals("speed")){
System.out.print("What is the distance in meters?: ");
d = input.nextDouble();
System.out.print("What is the time is seconds?: ");
t = input.nextDouble();
s = d / t;
System.out.println("The Speed is "+ s +" m/s");
System.out.println();
}
} //End of the while-loop
}
}
The first line of code within the while-loop is:
System.out.println("What would you like to calculate?: ");
So far so good. When I run the program, it prints: *What would you like to calculate?: *
And then the program continues as expected.
The problem is after the program reaches the end of the while-loop, and returns to the top of the while loop. it will print:
What would you like to calculate?:
What would you like to calculate?:
I just can't figure out why it prints it out twice.
Here is an example of the exact output I received when running the program (The italic is the output to the console and the bold is my input):
Start{
Hello, I am the Physics Calculator!!
What would you like to calculate?: speed
What is the distance in meters?: 50
What is the time is seconds?: 50
The Speed is 1.0 m/s
What would you like to calculate?:
What would you like to calculate?:
}End
At the end, I can still type 'speed' and continue on with the program. I just want to get rid of the second 'What would you like to calculate'.
Any input regarding the problem that I am having will be highly appreciated!!
Thank you very much for your time!!
This happens because nextDouble doesn't consume the newline that follows the number. You need to do that separately. Currently, that newline (after the number) gets consumed the next time you are prompted for a command. Since empty string is not "speed", the loop goes through one extra time.
Add Input.nextLine(); after t = Input.nextDouble(); and this will work just fine.
"if" statement only allows to put numbers in it.
Is there a way to make it read letters?
I'm only in my fifth lesson of Java (I study in a uni and the teacher is very slow but I want to learn things fast)
for example.
import java.util.Scanner;
public class Java {
public static void main (String [] args) {
Scanner scan = new Scanner(System.in);
int answer1;
System.out.println("Do you like Java?");
answer1 = scan.nextInt();
if (answer1 == yes)
System.out.println("Cool ~");
else
System.out.println("Ehh...");
}
}
I want to put "yes" instead of the number 5.
So if the user types "yes" it will print "correct".
P.S. I didn't find a clear answer to that in the search engine.
It's not a duplicated thread as I'm trying to find a clear answer to that.
I need a detailed explanation about it.
I'm still a beginner, using those "high tech java words" won't help me.
You need to modify your program so that your scanner to reads a String instead of an int. You can do that as:
import java.util.Scanner;
public class Java {
public static void main (String [] args) {
Scanner scan = new Scanner(System.in);
String answer1;
System.out.println("Do you like Java?");
answer1 = scan.next();
if (answer1.equals("yes"))
System.out.println("Cool ~");
else
System.out.println("Ehh...");
}
}
I used next() for this since we only want one word (token), but be aware that there are other options for reading Strings.
Notice also that I've changed the test in the condition because it's now a String. See this answer for more on comparing Strings.
You need to modify your program so that your scanner to reads a String instead of an int. You can do that as:
import java.util.Scanner; public class Java {
public static void main (String [] args) {
Scanner scan = new Scanner(System.in);
String answer1;
System.out.println("Do you like Java?");
answer1 = scan.next();
if (answer1.equals("yes"))
System.out.println("Cool ~");
else
System.out.println("Ehh...");
} }
I used next() for this since we only want one word (token), but be aware that there are other options for reading Strings.
Notice also that I've changed the test in the condition because it's
now a String. See this answer for more on comparing Strings.
Ok, what if you want the program to read both words and numbers:
Here's my program (more in depth, when you see the full thing), but this is one of 5 parts (that look a like) where I'm having the program...
public static void Gdr1() {
try {
System.out.print("[Code: Gdr1] Grade 1: %");
Scanner gdr1 = new Scanner(System.in);
Z = gdr1.next();
Z = Double.toString(Grd1);
Grd1 = Double.parseDouble(Z);
if ((Grd1<100)&&(Grd1>=5)) {
Gdr2();
} else if ((Grd1>=100)&&(Grd1<125)) {
System.out.println(" System> Great Job "+Stu+"!");
Gdr2();
} else if (Grd1<5) {
System.out.println("I'm sorry, the lowest grade I am allowed to compute is 5...");
Gdr1();
} else if (Z.equalsIgnoreCase("restart")) {
restart01();
} else {
System.out.println("("+Z+") cannot be resolved in my system...");
Gdr1();
}
} catch (Exception e) {}
}
Now everything works in the program, besides for when the End-User's input = "restart", I know some of the code in the program seems complicated, but it does work (most of it), can anyone help me try to figure this out, its for my portfolio at my school due latest by 1/25/2017 # 11:59 pm.
The things like Z (constant String), ""+Stu+"" (variable input), and [Code: Gdr1] are there for a purpose...