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 7 years ago.
Improve this question
//input: multiple integers with spaces inbetween
Scanner sc = new Scanner(System.in);
while(sc.hasNextInt())
{
//add number to list
}
sc.hasNextInt() is waiting for an integer. It only breaks out if you input a non-integer character.
I saw a solution here before not too long ago but i cant find it anymore.
The solution (was the best if you ask me) was using two scanners. I cant seem to figure out how it used two scanners to go around this problem.
sc.NextLine() maybe?
A user can input multiple integers the amount is unknown. Ex: 3 4 5 1. There is a space inbetween them. All i want to do is read the integers and put it in a list while using two scanners.
Based on your comment
A user can input multiple integers the amount is unknown. Ex: 3 4 5 1. There is a space inbetween them. All i want to do is read the integers and put it in a list while using two scanners.
You are probably looking for:
scanner which will read line from user (and can wait for next line if needed)
another scanner which will handle splitting each number from line.
So your code can look something like:
List<Integer> list = new ArrayList<>();
Scanner sc = new Scanner(System.in);
System.out.print("give me some numbers: ");
String numbersInLine = sc.nextLine();//I assume that line is in form: 1 23 45
Scanner scLine = new Scanner(numbersInLine);//separate scanner for handling line
while(scLine.hasNextInt()){
list.add(scLine.nextInt());
}
System.out.println(list);
Try this:
while (sc.hasNext()) {
if (sc.hasNextInt()) {
// System.out.println("(int) " + sc.nextInt());
// or add it to a list
}
else {
// System.out.println(sc.next());
// or do something
}
}
Scanner sc = new Scanner(System.in);
while(sc.hasNextInt())
{
System.out.println("Hi");
System.out.println("Do you want to exit ?");
Scanner sc2 = new Scanner(System.in);
if(sc2.next().equalsIgnoreCase("Yes")){
break;
}
}
Related
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 1 year ago.
Improve this question
Here is the code I have.
//input
System.out.println("Using numbers, in what month were you born? ");
String **userMonth** = input.nextLine();
// also tried int **userMonth** = input.nextInt();
It does not work either way.
userMonth will not "activate?" (sorry noob and don't know all terms)
When tried to call later in program error:
if (userMonth < 3) {
System.out.println("Your vacation home is a van down by a river!");
}
//userMonth cannot be resolved to variable
Very odd that your variables are showing up as **varName** instead of varName.
First use:
int userMonth = 0; // initialize variable.
userMonth = input.nextInt();
But it does not consume the newline ('ENTER').
Therefore, immediately after, consume the newline character via:
input.nextLine();
Also make sure Scanner was declared as
Scanner input = new Scanner(System.in);
Don't forget to close the scanner at the end of program
input.close();
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 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 4 years ago.
Improve this question
What I'm trying to do is validate a scanner so that if the input string doesn't have a minimum of two vowels it returns an error, however I'm not sure how to go about this and can't seem to find an answer elsewhere.
Scanner sc = new Scanner(System.in);
System.out.print("Input alphabetical character string: ");
while (!sc.hasNext("[aeiouAEIOU]+")) {
System.out.println("Error, sequence requires a minimum of two vowels");
sc.next();
}
you could use a validate method each time they enter a value something like this.this one only checks for each vowel once though.
public static void main(String[] args) {
// TODO Auto-generated method stub
String sInput = "";
Scanner sc = new Scanner(System.in);
System.out.print("Input alphabetical character string: ");
sInput = sc.next();
if (!hasTwoVowels(sInput)) {
System.out.println("Error, sequence requires a minimum of two vowels");
sc.next();
}
sc.close();
}
public static boolean hasTwoVowels(String sInput){
int iCount = 0;
String vowel[] = new String[]{"a","e","i","o","u","A","E","I","O","U"};
for(int i =0; i < 10;i++) {
if(sInput.contains(vowel[i])) {
iCount++;
if(iCount == 2) {
return true;
}
}
}
return false;
}
}
you could also split the string and count each letter then add up the vowels
you can easily do this by doing something like this.
arr[(int)'e' - (int)'a']++ that will increment arr[4] counting 1 e
you could also use a bufferedReader to count the vowels
This is a problem where using a Scanner makes the problem harder.
The simple solution is to just read the stream one character at a time using a BufferedReader and count the characters that are vowels.
You could do it by configuring a Scanner to return "tokens" consisting of a single character and then counting the tokens that match a vowel. But that's pointless ... IMO.
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.
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 9 years ago.
Improve this question
Hi i have a program that doesnt seem to be registering. I am fairly new so I would appreciate any help and there might be stupid mistakes made :/
But the point of the program is the enter a name and then find the name in a file called names.txt and then show the popularity of the name throughout the century. I currently have a program that doesnt seem to be working. Help Please
import java.io.*;
import java.util.Scanner;
public class Babynames{
public static void main (String[] args)throws FileNotFoundException{
Scanner reader = new Scanner(new File("names.txt"));
Scanner input=new Scanner(System.in);
System.out.print("What name would you like to search up: ");
String name = input.nextLine();
Scanner lineScan = new Scanner(name);
String thisname = lineScan.next();
if (name.equals(name))
{
while (lineScan.hasNextInt())
{
int next = lineScan.nextInt();
for (int i = 1900; i <=2000; i+=10)
{
System.out.print(i + next);
}
}
}
else
{
System.out.println("File not found! Try again: ");
String filename = input.nextLine();
Scanner lineScan2 = new Scanner(name);
}
}
}
Edit
it just asks for the name and after that the program ends
Your assignment seems to be:
Accept a baby name as input
find that name in a file that includes some information about that name
output the result which includes the info about the name.
From your code, I'm making an educated guess that a line in your file looks like:
name value value value value value value value value value value value
Where the values represent the popularity of the name 1900 - 2000 by decade (11 values)
So, your program would need to:
Get the user input (name) from System.in using a Scanner .
Open the file
Loop, reading a line from the file
Split the line by space (" ") into a String[] array
Compare the first element (array[0]) to see if it's your name
if it is, go through the rest of the array and output the values