Code:
int size=0;
Scanner in = new Scanner(System.in);
System.out.println("Enter size of the Graph");
size = in.nextInt();
System.out.println(size);
for (int i = 1; i <= size; i++) {
Scanner in2 =new Scanner(System.in);
while(in2.hasNextInt()){
int num = in2.nextInt();
System.out.print("(" + i + "," + num + ")"+",");
System.out.println();
}
System.out.println("out of the while loop");
}
Input & Output:
Enter size of the Graph
4
4
2 3 4
(1,2),
(1,3),
(1,4),
2 5 6
(1,2),
(1,5),
(1,6),
As you can see my program doesn't exists while loop. It still prints the value for i=1.
What I am doing wrong?
Your program is constantly waiting for a new feed, in order to terminate it - you should indicate the input was ended (or provide a non int input).
To indicate the feed ended - you should provide EOF - which is ctrl+D in linux and ctrl+Z in windows.
int num = in2.nextInt();
try adding in2.nextLine(); after that.
Note:
You shouldn't be doing new Scanner(System.in); multiple times.
Scanner in2 = new Scanner(System.in); // this is useless just use in
Related
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 2 years ago.
I am feeling quite stupid at this point for not being able to figure out something that is most likely a simple fix. I keep getting the error "Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:662)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at searchSorting.main(searchSorting.java:15)" after inputting how many numbers I want to input. Others solutions to this problem just don't seem to apply to me somehow. Thanks for the help
import java.util.Scanner;
import java.util.Arrays;
public class searchSorting
{
public static void main (String[]args)
{
String line;
int number, search, item, array[], first, last, middle;
Scanner in = new Scanner(System.in);
System.out.print("How many numbers you want to input?: ");
number = in.nextInt();
array = new int [number];
item = Integer.parseInt(in.nextLine());
double[] values = new double[item];
for (int i = 0; i < values.length; i++) {
System.out.print("Input number " + i + ": ");
values[i] = Double.parseDouble(in.nextLine());
}
for (int index = 0; index < 5; index++)
System.out.print(values[index] + " ");
in.nextLine();
Arrays.sort(values);
System.out.println("Sorted number is: " + Arrays.toString(values));
System.out.println("Enter the number you are looking for?");
search = in.nextInt();
first = 0;
last = (item - 1);
middle = (first + last)/2;
while( first <= last )
{
if ( array[middle] < item )
first = middle + 1;
else if ( array[middle] == item )
{
System.out.println(item + " found at location " + (middle + 1) + ".");
break;
}
else
{
last = middle - 1;
}
middle = (first + last)/2;
}
if ( first > last )
System.out.println(item + " is not found.\n");
}}
For more info check out Scanner and Integer documentation, it's an excellent resource.
Edit: Try removing line 15 and replacing item with number in the next line
You call this:
number = in.nextInt();
Assuming the user types 123 and ENTER, this call consumes the 123 and leaves the input stream positioned before the end-of-line character.
The next relevant code is
item = Integer.parseInt(in.nextLine());
The nextLine call advances the input stream past the end-of-line, returning all characters it passed on the way. Since the ENTER key was pressed immediately after 123, the returned value is the emoty string. Which is not an integer.
You need to review your strategy of sometimes scanning numbers (nextInt) and sometimes scanning rest-of-linr (nextLine). Mixing the two needs to be done quite carefully. You might be better advised to stick to the numerical methods (nextInt/nextDouble).
For example, replacing this
item = Integer.parseInt(in.nextLine());
by this
item = in.nextInt();
automatically handles the line-ending.
From discussion in comments:
I am still confused as to why it's having me input
the value a second time on the next line
Making assumptions about how you modified the code since your initial question: it's because you've written code that reads the number twice:
System.out.print("How many numbers you want to input?: ");
number = in.nextInt(); // **** first input ****
array = new int [number];
item = in.nextDouble(); // **** second input ****
double[] values = new double[item];
Each time you call for in.nextSomething() the Scanner is going to read more input. It should likely just be this:
System.out.print("How many numbers you want to input?: ");
number = in.nextInt();
array = new int [number];
double[] values = new double[number];
(I'm a beginner at Java)
I am trying to write a program that asks for 6 digits from the user using a scanner, then from those 6 individual digits find the second highest number. So far this works however I'd like to have the input read from a single line rather than 6 separate lines. I've heard of delimiters and tokenisation, but have no idea how to implement it. I'ld like to have it read like "Enter 6 digits: 1 2 3 4 5 6" and parsing each digit as a separate variable so i can then place them in an array as shown. If anyone could give me a run-down of how this would work it would be much appreciated. Cheers for your time.
public static void main(String[] args)
{
//Ask user input
System.out.println("Enter 6 digits: ");
//New Scanner
Scanner input = new Scanner(System.in);
//Assign 6 variables for each digit
int num1 = input.nextInt();
int num2 = input.nextInt();
int num3 = input.nextInt();
int num4 = input.nextInt();
int num5 = input.nextInt();
int num6 = input.nextInt();
//unsorted array
int num[] = {num1, num2, num3, num4, num5, num6};
//Length
int n = num.length;
//Sort
Arrays.sort(num);
//After sorting
// Second highest number is at n-2 position
System.out.println("Second highest Number: "+num[n-2]);
}
}
Your solution does this allready!
If you go through the documentation of scaner you will find out that your code works with different inputs, as long they are integers separated by whitespace and/or line seperators.
But you can optimice your code, to let it look nicer:
public static void main6(String[] args) {
// Ask user input
System.out.println("Enter 6 digits: ");
// New Scanner
Scanner input = new Scanner(System.in);
// Assign 6 variables for each digit
int size=6;
int[] num=new int[size];
for (int i=0;i<size;i++) {
num[i]=input.nextInt();
}
Arrays.sort(num);
// After sorting
// Second highest number is at n-2 position
System.out.println("Second highest Number: " + num[size - 2]);
}
As an additional hint, i like to mention this code still produces lot of overhead you can avoid this by using:
public static void main7(String[] args) {
// Ask user input
System.out.println("Enter 6 digits: ");
// New Scanner
Scanner input = new Scanner(System.in);
// Assign 6 variables for each digit
int size=6;
int highest=Integer.MIN_VALUE;
int secondhighest=Integer.MIN_VALUE;
for (int i=0;i<size-1;i++) {
int value=input.nextInt();
if (value>highest) {
secondhighest=highest;
highest=value;
} else if (value>secondhighest) {
secondhighest=value;
}
}
//give out second highest
System.out.println("Second highest Number: " + secondhighest);
}
if you do not like to point on highest if there are multiple highest, you can replace the else if:
public static void main7(String[] args) {
// Ask user input
System.out.println("Enter 6 digits: ");
// New Scanner
Scanner input = new Scanner(System.in);
// Assign 6 variables for each digit
int size = 6;
int highest = Integer.MIN_VALUE;
int secondhighest = Integer.MIN_VALUE;
for (int i = 0; i < size - 1; i++) {
int value = input.nextInt();
if (value > highest) {
secondhighest = highest;
highest = value;
} else if (secondhighest==Integer.MIN_VALUE&&value!=highest) {
secondhighest=value;
}
}
// give out second highest
System.out.println("Second highest Number: " + secondhighest);
}
Of course, there are many ways to do that. I will give you two ways:
1. Use lambda functions - this way is more advanced but very practical:
Integer[] s = Arrays.stream(input.nextLine().split(" ")).map(Integer::parseInt).toArray(Integer[]::new);
first create a stream, you can read more about streams here
than read the whole line "1 2 3 ...."
split the line by space " " and after this point the stream will look like ["1", "2", "3" ....]
to convert the strings to int "map" operator is used
and finally collect the stream into Integer[]
You can use an iterator and loop as many times as you need and read from the console.
int num[] = new int[6];
for (int i = 0; i < 6; i++) {
num[i] = input.nextInt();
}
There are several ways to do that:
take a single line string, then parse it.
Scanner input = new Scanner(System.in);
....
String numString = input.nextLine();
String[] split = numString.split("\\s+");
int num[] = new int[split];
// assuming there will be always atleast 6 numbers.
for (int i = 0; i < split.length; i++) {
num[i] = Integer.parseInt(split[i]);
}
...
//Sort
Arrays.sort(num);
//After sorting
// Second highest number is at n-2 position
System.out.println("Second highest Number: "+num[n-2]);
Code:
public class Adddemo {
public static void main(String[] args) throws IOException {
int i, j, k;
System.out.println("enter value of i: ");
i = (int) System.in.read();
System.out.println("enter value of j: ");
j = (int) System.in.read();
k = i + 1;
System.out.println("sum is: " + k);
}
}
Is System.in.read used for multiple inputs?
System.in.read() is used to read a character.
suppose you enter 12, then i becomes 1(49 ASCII) and j becomes 2(50 ASCII).
suppose you enter 1 and then press enter, i becomes (ASCII 49) and enter(ASCII 10), even enter is considered a character and hence skipping your second input.
use a scanner or bufferedReader instead.
Using a scanner
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
int j = sc.nextInt();
int k = i + j;
System.out.println(k);
Using a BufferedReader
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int i = Integer.parseInt(reader.readLine());
int j = Integer.parseInt(reader.readLine());
int k = i + j;
System.out.println(k);
System.in.read() doesn't read a number, it reads one byte and returns its value as an int.
If you enter a digit, you get back 48 + that digit because the digits 0 through 9 have the values 48 through 57 in the ASCII encoding.
To read a number from System.in you should use a Scanner.
use Scanner class instead:
import java.util.Scanner;
public class Adddemo {
public static void main(String[] args) throws IOException {
Scanner read=new Scanner(System.in);
int i,j,k;
System.out.println("enter value of i: ");
i=(int)read.nextInt();
System.out.println("enter value of j: ");
j=(int)read.nextInt();
k=i+1;
System.out.println("sum is: "+k);
}
}
System.in.read() reads 1 byte at a time.
if you want to feed your input values for i and j , do this
Leave one space between 1 and 2 while giving input in console
1 will be taken as value for i
2 will be taken as value for j
giving input as 12 (no spaces) will also yield the same result, cuz each byte is considered as an input
program
int i,j;
char c,d;
System.out.println("enter value of i: ");
i=(int)System.in.read();
System.out.println("enter value of j: ");
j=(int)System.in.read();
System.out.println("i is: "+i);
System.out.println("j is: "+j);
Output:
enter value of i,j:
1 2 //leave one space
i is: 1
j is: 2
let me know if you didn't understand yet
I have a programming assignment that's asking me to have the user input 10 (or less) integers and put them in an array, then take the average of them and output it. If they input a period, the program should stop asking for integers and do the averaging.
My problem is that whenever the user inputs an integer, the for loop executes more than once.
My code is below. Any ideas on how to fix this?
int[] intArr = new int[10];
int entered;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for(entered = 0; entered < 10; entered++){
System.out.println("Please enter an integer: ");
int input = br.read();
if(input == '.') break;
else{
intArr[entered] = input;
}
}
int total = 0;
for(int i : intArr){
total += i;
}
System.out.println("Average: " + total/entered);
System.out.println("Entered: " + entered);
Use String input = br.readLine() to read an entire line.
To check for ".", use if (input.equals(".")) { ... }.
(check out this if you want to know why you have to use .equals() instead of == for Strings)
Finally, to convert the input to an integer, see here.
for (entered = 0; entered < 10; entered++) {
System.out.println("Please enter an integer: ");
String str = br.readLine();
if (".".equals(str)) {
break;
}
int input = Integer.valueOf(str);
intArr[entered] = input;
}
Ok Its Really Simple
First let Me Explain You Why Its Happening
Ok the read() function reads first char of the input value and rest of line is stored in buffer
so when you enter any integer
for example: 1
1 is stored in variable and '\n'which java by defaults adds to a input value gets stored in buffer
so in next iteration of loop
it reads the char '\n' from buffer as input value and moves to next iteration
EXAMPLE 2:
If In Your Program We Enter Input As 12
It Skips Two Iterations
Coz Firstly It Stores 1 At The Time Of Input
In Next Iteration It Takes value 2 of previous input as input for this time
In Further Next Iteration It Takes '\n'
and then moves to next iteration at which their is no character left in memory so it asks you to input
Note:::
read() functions return character so even if user enters 5 while calculation ASCII Code Of 10 will be used that is 53 not one creating problems
FIX:::
int[] intArr = new int[10];
int entered;
BufferedReader br = new BufferedReader(new InputStreamReader(System. in ));
for (entered = 0; entered < 10; entered++) {
System.out.println("Please enter an integer: ");
String input = br.readLine();
if (input.equals(".")) {
break;
} else {
intArr[entered] = Integer.parseInt(input);
}
}
int total = 0;
for (int i: intArr) {
total += i;
}
System.out.println("Average: " + total / entered);
System.out.println("Entered: " + entered);
I have a small task that allows the user to enter the regions and their neighbors of any country.
I did everything and I just have a small problem which is when I run my code and the program asks the user to enter the number of regions, if the user enters 13 or and number greater than 10, the system will consider that number is like two inputs and it will not allow the user to enter anything for the second question and it will prompt him with the third question immediately. Why?
I think the problem with the Scanner class in the following command:
Scanner kb = new Scanner(System.in);
System.out.print("Please enter the number of regions: ");
int REGION_COUNT = kb.nextInt();
region = new CountryRegion[REGION_COUNT];
String[] neighbours;
for (int r = 0; r < region.length; r++) {
System.out.print("Please enter the name of region #" + (r + 1) + ": ");
String regionName = kb.nextLine();
System.out.print("How many neighbors for region #" + (r + 1) + ": ");
if (kb.hasNextInt()) {
int size = kb.nextInt();
neighbours = new String[size];
for (int n = 0; n < size; n++) {
System.out.print("Please enter the neighbour #" + (n + 1) + ": ");
neighbours [n] = kb.nextLine();
}
region [r] = new CountryRegion(regionName, neighbours);
}
else
System.exit(0);
}
for (int i = 0; i < REGION_COUNT; i++) {
System.out.print(region[i].getRegionName() +": ");
for (int k = 0; k < region[i].getRegionAjesint().length; k++) {
System.out.print(region[i].getRegionAjesint()[k] +", ");
}
System.out.println();
}
mapColor = new MapColor(region);
Any help, please?
Ok, Very simple your problem is that you are using the nextInt() method of the Scanner class and then using the nextLine() method both of these use the same buffer and here is what's happening.
When you enter the number your asking (let say 10) in the key board your actually entering
10 and the enter key (new line character (\n))
The nextInt() method from the Scanner class will read the 10 and just the 10 that meaning that the new line character (\n) is still in the keyboard buffer and next in your code you have a nextLine() which will read everything up to a new line (\n), which you already have in the buffer!!!
So the way this is all working is that the nextLine() method considers the new line character (\n) left in the buffer as it's input and there for continues to the next iteration of the loop.
The solution to your problem is to clear the buffer of the new line character (\n) you can achieve this by calling a nextLine() method before the actual one in your code like so:
...
int REGION_COUNT = kb.nextInt();
region = new CountryRegion[REGION_COUNT];
String[] neighbours;
kb.nextLine(); //CLEAR THE KEYBOARD BUFFER
for (int r = 0; r < region.length; r++) {
System.out.print("Please enter the name of region #" + (r + 1) + ": ");
String regionName = kb.nextLine();
...
This way the nextLine() called extracts the new line character from the buffer, clearing it, and since it doesn't store it it gets discarded leaving you with a new line character free buffer ready to receive full input from the user in your nextLine() method.
Hope this helps.
Sounds like each key press is an input.
You are using nextLine() to get the String but I think you should be using next().