Confusion with Scanners (Big Java Ex 6.3) - java

Currently reading Chapter 6 in my book. Where we introduce for loops and while loops.
Alright So basically The program example they have wants me to let the user to type in any amount of numbers until the user types in Q. Once the user types in Q, I need to get the max number and average.
I won't put the methods that actually do calculations since I named them pretty nicely, but the main is where my confusion lies.
By the way Heres a simple input output
Input
10
0
-1
Q
Output
Average = 3.0
Max = 10.0
My code
public class DataSet{
public static void main(String [] args)
{
DataAnalyze data = new DataAnalyze();
Scanner input = new Scanner(System.in);
Scanner inputTwo = new Scanner(System.in);
boolean done = false;
while(!done)
{
String result = input.next();
if (result.equalsIgnoreCase("Q"))
{
done = true;
}
else {
double x = inputTwo.nextDouble();
data.add(x);
}
}
System.out.println("Average = " + data.getAverage());
System.out.println("Max num = " + data.getMaximum());
}
}
I'm getting an error at double x = inputTwo.nextDouble();.
Heres my thought process.
Lets make a flag and keep looping asking the user for a number until we hit Q. Now my issue is that of course the number needs to be a double and the Q will be a string. So my attempt was to make two scanners
Heres how my understanding of scanner based on chapter two in my book.
Alright so import Scanner from java.util library so we can use this package. After that we have to create the scanner object. Say Scanner input = new Scanner(System.in);. Now the only thing left to do is actually ASK the user for input so we doing this by setting this to another variable (namely input here). The reason this is nice is that it allows us to set our Scanner to doubles and ints etc, when it comes as a default string ( via .nextDouble(), .nextInt());
So since I set result to a string, I was under the impression that I couldn't use the same Scanner object to get a double, so I made another Scanner Object named inputTwo, so that if the user doesn't put Q (i.e puts numbers) it will get those values.
How should I approach this? I feel like i'm not thinking of something very trivial and easy.

You are on the right path here, however you do not need two scanners to process the input. If the result is a number, cast it to a double using double x = Double.parseDouble(result) and remove the second scanner all together. Good Luck!

Related

Finding hashtags in a input string from a user [duplicate]

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 want to read those inputs in a single line separated by space in java without using String?

System.out.println("Number of pages + Number of lost pages + Number of Readers");
int n = s.nextInt();
int m = s.nextInt();
int q = s.nextInt();
I want to read input values all the values are going to be integer but I want to read it in a same line with changing it form Integer.
Assuming s is an instance of Scanner: Your code, as written, does exactly what you want.
scanners are created by default with a delimiter configured to be 'any whitespace'. nextInt() reads the next token (which are the things in between the delimiter, i.e. the whitespace), and returns it to you by parsing it into an integer.
Thus, your code as pasted works fine.
If it doesn't, stop setting up a delimiter, or reset it back to 'any whitespace' with e.g. scanner.reset(); or scanner.useDelimiter("\\s+");.
class Example {
public static void main(String[] args) {
var in = new Scanner(System.in);
System.out.println("Enter something:");
System.out.println(in.nextInt());
System.out.println(in.nextInt());
System.out.println(in.nextInt());
}
}
works fine here.

Adding unknown number of numbers to arraylist

I'm trying to make an Insertion Sort algorithm in Java, and I want it to read user input, and he/she can put however many numbers they wish (We'll say they're all integers for now, but long run it would be nice to be able to do both integers and doubles/floats), and I want the algorithm to sort them all out. My issue is that when I run this code to see if the integers are adding correctly, my loop never stops.
public class InsertionSort {
public static void main(String[] args){
System.out.println("Enter the numbers to be sorted now: ");
ArrayList<Integer> unsortNums = new ArrayList<Integer>();
Scanner usrIn = new Scanner(System.in);
while(usrIn.hasNextInt()) {
unsortNums.add(usrIn.nextInt());
System.out.println(unsortNums); //TODO: Doesn't stop here
}
sortNums(unsortNums);
}
}
Now, I suspect it has something to do with how the scanner is doing the .hasNextInt(), but I cannot for the life of me figure out why it isn't stopping. Could this be an IDE specific thing? I'm using Intellij Idea.
Let me know if I left anything out that I need to include.
Your code will stop as long as you stop adding numbers to your input stream. nextInt() is looking for another integer value, and if it can't find one, it'll stop looping.
Give it a try - enter in any sequence of characters that can't be interpreted as an int, and your loop will stop.
As a for-instance, this sequence will cease iteration: 1 2 3 4 5 6 7 8 9 7/. The reason is that 7/ can't be read as an int, so the condition for hasNextInt fails.
When using a scanner on System.in, it just blocks and waits for the user's next input. A common way of handling this is to tell the user that some magic number, e.g., -999, will stop the input loop:
System.out.println("Enter the numbers to be sorted now (-999 to stop): ");
List<Integer> unsortNums = new ArrayList<Integer>();
Scanner usrIn = new Scanner(System.in);
int i = usrIn.nextInt();
while(i != -999) {
unsortNums.add(i);
i = usrIn.nextInt();
}

How to compare a variable to see if it's the right class type?

I've been learning Java from scratch again since 2 years of rust, and I was playing around with a simple random generator code. My issue here is that when the user is asked what he wants as his highest die roll, it must be a number (int) class type.
I was trying to create an if statement and compare a variable to its class, rather than letting my IDE stop and show me an error message in a case the user typed letters.
Here is my code (It's the simplest code ever but it's safe to say that I'm new and motivating myself to learn Java again.) :
package firstguy;
import java.util.Random;
import java.util.Scanner;
public class randomnum {
public static void main(String[] args){
Random dice = new Random();
Scanner userin = new Scanner(System.in);
int number;
int highnum;
System.out.println("What's the highest roll you want? \n");
highnum = userin.nextInt();
for(int counter=1; counter<= highnum; counter++){
number= 1 + dice.nextInt(highnum);
System.out.println("This is the number " + number);
}
}
}
I want to be able to compare highnum, here to see if it stays as the class type int and not a letter. In case a letter or a character is typed, a message should be displayed or the question should be repeated. I've been trying to look for this problem but I keep getting results of comparing two variables of the same class type.
Is there no way to compare a variable to a class type?
Primitive types of Java do not have a class. Their wrapper types do, but your code does not use them.
What you are trying to do is to check end-user input for presence of character combinations that represent an integer vs. everything else. This is relatively easy to do, because Scanner provides methods hasNext... for various data types. You can use hasNextInt() in a loop, discarding the unwanted input, like this:
System.out.println("What's the highest roll you want? \n");
while (!userin.hasNextInt()) {
System.out.println("Please enter an integer.");
userin.nextLine();
}
// Since we reached this point, userin.hasNextInt() has returned true.
// We are ready to read an integer from the scanner:
highnum = userin.nextInt();
nextInt() (or most other nextXYZ methods, for that matter), throw an InputMismatchException if they encounter input that doesn't match their call (e.g., a letter in a nextInt call). So one option would be to simply catch it:
int highnum;
try {
highnum = userin.nextInt();
} catch (InputMismatchException e) {
System.out.println ("Wrong input encountered");
}
What you're looking for is not a way to "compare a variable to a class type", but rather to check a String to see if it has the right format. If you want to see if a String consists only of digits, the simplest way is using matches and a regular expression:
if (inputString.matches("\\d+")) {
... the input is valid
} else {
... complain
}
The regular expression here means "one or more digits". You could also use hasNextInt on a Scanner, or use nextInt on a Scanner and catch exceptions, or use Integer.parseInt(inputString) and catch exceptions, just to name a few.
try this:
boolean go = true;
System.out.println("What's the highest roll you want? \n");
while(go){
try{
highnum = userin.nextInt();
go = false;
catch(Exception e){
System.out.println("Please type in an integer: ");
highnum = userin.nextInt();
}
}

How do i declare and read values into integer values?

I'm really new to java and i'm taking an introductory class to computer science. I need to know how to Prompt the user to user for two values, declare and define 2 variables to store the integers, and then be able to read the values in, and finally print the values out. But im pretty lost and i dont even know how to start i spent a whole day trying.. I really need some help/guidance. I need to do that for integers, decimal numbers and strings. Can someone help me?
You can do this by using Scanner class :
A simple text scanner which can parse primitive types and strings using regular expressions.
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.
For example, this code allows a user to read a number from System.in:
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
int j = scan.nextInt();
System.out.println("i = "+i +" j = "+j);
nextInt() : -Scans the next token of the input as an int and returns the int scanned from the input.
For more.
or to get user input you can also use the Console class : provides methods to access the character-based console device, if any, associated with the current Java virtual machine.
Console console = System.console();
String s = console.readLine();
int i = Integer.parseInt(console.readLine());
or you can also use BufferedReader and InputStreamReader classes and
DataInputStream class to get user input .
Use the Scanner class to get the values from the user. For integers you should use int, for decimal numbers (also called real numbers) use double and for strings use Strings.
A little example:
Scanner scan = new Scanner(System.in);
int intValue;
double decimalValue;
String textValue;
System.out.println("Please enter an integer value");
intValue = scan.nextInt(); // see how I use nextInt() for integers
System.out.println("Please enter a real number");
decimalValue = scan.nextDouble(); // nextDouble() for real numbers
System.out.println("Please enter a string value");
textValue = scan.next(); // next() for string variables
System.out.println("Your integer is: " + intValue + ", your real number is: "
+ decimalValue + " and your string is: " + textValue);
If you still don't understand something, please look further into the Scanner class via google.
As you will likely continue to run into problems like this in your class and in your programming career:
Lessons on fishing.
Learn to explore the provided tutorials through oracle.
Learn to read the Java API documentation
Now to the fish.
You can use the Scanner class. Example provided in the documentation.
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();

Categories