Scanner object executes only one time in while loop - java

I have a situation where the program will take input for total no of string to be inputted.
Once inputted it will print odd and even indexes of the string in one line separated by a space.
For illustration this should be the output for the follwing input:
2
input
ipt nu
output
otu upt
my logic seems fine but when I am trying to execute the program runs for only one time whatever be the input. Can anyone please let me know what am I missing here.
Code snippet
import java.util.Scanner;
public class javatest
{
static Scanner scan = new Scanner(System.in);
public static void main(String[] args)
{
String input_string;
int inputs = scan.nextInt();//total inputs to be accepted
int i=0;
while(i<inputs)
{
input_string = scan.nextLine();
//for even places
for (int j = 0; j < input_string.length(); j += 2)
{
if (j % 2 == 0)
{
System.out.print(input_string.charAt(j));
}
}
System.out.print(" ");
//for odd places
for (int k = 1; k < input_string.length(); k += 2)
{
if (k % 2 == 1)
{
System.out.print(input_string.charAt(k));
}
}
i++;
}
}
}
The above code is producing the output as
3
hello
hlo el
(execution ended)

The issue is that scan.nextInt() does not read the enter pressed while inputing the number. Due to this issue your program runs 1 iteration lesser than the input.
I ran your exact code without any modification and it runs twice for input 3.
The first call to scan.nextLine() gives an empty string.
The alternative can be replacing
scan.nextInt() with Integer.valueOf(scan.nextLine());
which will read the enter/new line character also.

By pressing enter upon entering the amount of inputs you are creating a newline \n character which is consumed by the input_string = scan.nextLine(); in your while loop. So directly after entering the amount of inputs the while loop will increment the value of i to 1 as it processes the \n character.
As a workaround you could fetch the amount of expected inputs as a String and parse it to an int like this:
int inputs = 0;
try {
inputs = Integer.parseInt(scan.nextLine());
} catch (NumberFormatException e) {
// handle exception gracefully, maybe by showing a message to the user.
}
Also to make it more clear for the user to understand that an input is expected you might want to add a message that makes it clear a new input is expected:
System.out.println("Please provide the next input: ");
input_string = scan.nextLine();

Related

Java Project Output

Hi I'm finishing an assignment, however I'm getting the wrong output.
The goal of the project is to reverse a string.
So it's supposed to take in a line of text as input, and outputs that line of text in reverse. The program repeats, ending when the user enters "Done", "done", or "d" for the line of text.
Ex: If the input is:
Hello there
Hey
done
the output is:
ereht olleH
yeH
My code:
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String str;
while (true) {
str = scnr.nextLine();
if (str.equals("quit") || str.equals("Quit") || str.equals("q")) break;
for (int i = 0; i < str.length(); i++) {
System.out.print(str.charAt(str.length() - i - 1));
}
System.out.println();
}
}
}
My current code is that however output is coming back as:
Input
Hello there
Hey
done
Output
ereht olleH
yeH
enod
Expected output
ereht olleH
Cannot figure out what I'm doing wrong.
/*
I don't know what you know, so I am not sure how your professor
wants you to complete this, but I will do what comes to mind for myself.
*/
//Instead of while(true) I like to use do while, which runs once automatically, and continues running until a condition is met
do {
str = scnr.nextLine();
int i = 0;
//This isn't the cleanest way to solve this, especially because it doesn't remove the space before done.
//You could add more if statements for that, but the cleanest way would be to split the words into a String array
// and check if any of the values of the array equal done, and remove it before flipping it around
if(str.toLowerCase().contains("done"))
i = 4;
else if(str.toLowerCase().contains("d"))
i = 1;
while (i < str.length()) {
System.out.print(str.charAt(str.length() - i - 1));
i++;
}
System.out.println();
}
while (!str.toLowerCase().contains("done") || !str.toLowerCase().contains("d")); //This replaces that if statement from before
you are using .equals() to check if the line is equal to one of your break words, but you are giving it the input Hello there Hey done, so it will not detect the the break word (ignoring the fact that you gave it done, not quit, I'm assuming that was a typo), so to detect that, you would either have to check if the line contains that word and if so, toggle a boolean and remove the word and any text after it from the line, e.g:
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String str;
boolean end = false;
while (!end) {
str = scnr.nextLine();
if (str.contains("quit") || str.contains("Quit") || str.contains("q")) { // checks if str contains the word, so if you write "hello quit" it will still detect it.
str = str.substring(0,str.toLowerCase().indexOf("q")); // cuts off the string from the q.
end = true;
}
for (int i = 0; i < str.length(); i++) {
System.out.print(str.charAt(str.length() - i - 1));
}
System.out.println();
}
}
otherwise, you would just need to add the quit to the line after, and then it would work, so you would put in Hello there Hey then press enter, and then quit, and that will work.

For loop that takes user input 5 times

I was to make a for loop that repeats 5 times. Each time it asks you to enter a grade, takes your input using System.in.read();, then says what you entered. For some reason the output looks strange and it isn't working right. The output looks like this:
Enter a letter grade for your class
(the letter you enter ex. a)
Grade entered = a
Enter a letter grade for your class
Grade entered =
the above repeats 3 times then ends with the "thanks, keep up the good work!" line ^
The output should look like
Enter a letter grade for your class
(entered letter ex. b)
Grade entered = b
And it does this 5 times ^
Sorry if it isn't indented properly or the solution is obvious, new to programming.
char g;
{
for (int x = 0; x < 5; x++) {
System.out.println("Enter a letter grade for your class");
g = (char) System.in.read();
System.out.println("Grade entered = " + g); }
System.out.println("Thanks, keep up the good work!"); }
Some points regarding your code. Firstly, format it correctly. Your problem currently is that your for-loop is only running for the System.out.println statement, and the rest is ignored. Don't omit brackets when you write for-loops, its not a very good habit. Since this is homework, I will not give you the code, but I will give you the code structure:
public class Main {
public static void main(String[] args) {
for (int x = 0; x < 5; x++) { //looping 5 times
System.out.println("Enter a letter grade for your class"); //print statement
//code here to get character
System.out.println("Grade entered = " + g);
}
//print final statement outside the for-loop.
System.out.println("Thanks, keep up the good work!");
}
}
Next point: I would not recommend using System.in.read() for reading the input from the console. Reason for this, is because it will include the carriage return when you press 'Enter' - you would need to specifically look out for that in your code. In order to avoid this, use a Scanner, and get the first character of the returned Scanner string using charAt(0).

Java loop for double working

I wrote a loop, but it doesn't work. It should ask me 4 times for a and for every a it should write numbers from 0 to 3. But after asking it writes two numbers. Where is mistake?
My code is
package hra1;
public class Hra1 {
public static void main(String args[]) throws java.io.IOException
{
char a;
int i;
for (i = 0; i < 4; i++)
{
a = (char) System.in.read();
System.out.println(i);
}
}
}
Here is an example of the output:
l
0
1
l
2
3
When you type one character and then press the enter key (<-|), the system delivers two characters to your program; hence 0 and 1 are printed after typing the first 'l' and 2 and 3 after typing the second 'l'.
You might print the codepoint of the character read, e.g.,
for (int i = 0; i < 4; i++){
char a = (char) System.in.read();
System.out.println( Character.getNumericValue( a ) );
}
in the loop to see what is going on.
Your code is also reading the newline character('\n') as you are hitting the enter key('\n') after every input('1','2','3' etc).
If you type one character and press enter key,System.in.read() will read two characters as it also reads the newline character.
Re-factored your code a bit.
Enter all the values in one line(do not press enter key until you enter all the values). This will solve your problem.
for (i = 0; i < 4; i++)
{
a = (char)System.in.read();
System.out.println(a);
}
Input 4567
Output
4
5
6
7
The ideone code link is here http://ideone.com/IYcjyX. Hope it helps.
enter key -> "\n"
So, your input 1\n
You are actually providing two inputs that are being read when you enter a number in the terminal. First, your integer (e.g. '1'), then a newline character ('\n') when you hit the enter key.
Another method to achieve what you want is to use the Scanner class, like so:
package hra1;
public class Hra1 {
public static void main(String args[])
throws java.io.IOException
{
int i;
Scanner scanner = new Scanner(System.in);
for (i = 0; i < 4; i++)
{
// Scan the next token of input as an integer
int a = scanner.nextInt();
System.out.println(i);
}
}
}
System.in is an InputStream - read() reads exactly one byte. Your direct input is more than one byte and so both values are directly read within the first input.
The program will try to run again the for loop in order to read the next byte of the input.That's why when you give an input that is more than 1 byte,the system try to read the other bytes and system.out.println will be executed more than 1 times.

How to input a lot of data until you type in an invalid number in java

User inputs numbers one by one and then once they type in an invalid number (has to be from 1-200) the program calculates the average of the numbers that were inputted.
I'm just wondering what would the code be for this. I know the one for inputting one piece of data. Example would be:
`Scanner in = new Scanner(System.in);
String numberOfShoes = "";
System.out.println("Enter the number of shoes you want: (0-200) ");
numberOfShoes = in.nextLine();`
this is just an example, but this time I want the user to input a lot of numbers. I know I'm going to include a loop somewhere in this and I have to stop it once it contains an invalid number (using a try catch block).
* I would also like to add that once the user inputs another number it always goes to the next line.
Just use a while loop to continue taking input until a condition is met. Also keep variables to track the sum, and the total number of inputs.
I would also suggest having numberOfShoes be an int and use the nextInt() method on your Scanner (so you don't have to convert from String to int).
System.out.println("Enter your number of shoes: ");
Scanner in = new Scanner(System.in);
int numberOfShoes = 0;
int sum = 0;
int numberOfInputs = 0;
do {
numberOfShoes = in.nextInt();
if (numberOfShoes >= 1 && numberOfShoes <= 200) { // if valid input
sum += numberOfShoes;
numberOfInputs++;
}
} while (numberOfShoes >= 1 && numberOfShoes <= 200); // continue while valid
double average = (double)sum / numberOfInputs;
System.out.println("Average: " + average);
Sample:
Enter your number of shoes:
5
3
7
2
0
Average: 4.25
It added 5 + 3 + 7 + 2 to get the sum of 17. Then it divided 17 by the numberOfInputs, which is 4 to get 4.25
you are almost there.
Logic is like this,
Define array
Begin Loop
Accept the number
check if its invalid number [it is how u define a invalid number]
if invalid, Exit Loop
else put it in the array
End Loop
Add all numbers in your array
I think you need to do something like this (which #Takendarkk suggested):
import java.util.Scanner;
public class shoes {
public void main(String[] args){
int input = 0;
do{
Scanner in = new Scanner(System.in);
String numberOfShoes = "";
System.out.println("Enter the number of shoes you want: (0-200) ");
numberOfShoes = in.nextLine();
input = Integer.parseInt(numberOfShoes);
}while((input>=0) && (input<=200));
}
}
you can use for loop like this
for(::)
{
//do your input and processing here
if(terminating condition satisified)
{
break;
}
}

Trying to find if there are at least 2 words in a string

I am trying to find out if a phrase entered by the user has at least 2 words in it. If it does not, keep asking them to enter a phrase until they enter one with at least 2 words.
Here is my code so far: It can successfully detect if they have entered 2 words, and it successfully detects if they don't enter 2 words the FIRST time, but if they enter below 2 words again the second time the program quit.
private static void stringfunctions() {
String phrase;
int count = 0;
Scanner input = new Scanner(System.in);
while (count < 2) {
System.out.println("Please enter a multiple word phrase: ");
phrase = input.nextLine();
String[] arrPhrase = phrase.split(" ");
for (int i = 0; i < arrPhrase.length; i++) {
if (arrPhrase[i].equals(" ")) {
} else {
count++;
}
}
}
reset count after testing. the problem is the while loop terminates as soon as count passes 2
Since this is homework, I'm not going to give you the answer, but watch closely the value of count as you travel through the loop.

Categories

Resources