Java loop for double working - java

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.

Related

Issue with reading input in java

I wrote a program that uses inbuilt stack API in java.
Stack <Integer> stack = new Stack<>();
int n = in.nextInt(); // number of instructions
in.nextLine(); // code to consume \n left out after nextInt()
String str="";
for(int i=0 ; i<n ; i++)
{
str = in.nextLine(); // Instructions for operations. Ex: 1) + 20 (pushes 20 to stack) 2) - (pops item)
char ch = str.charAt(0);
if(ch=='+')
stack.add(Integer.parseInt(str.substring(1).trim()));
else
System.out.println(stack.pop());
}
System.out.println(str); //statement that I wrote to debug
This works fine if I enter input line by line i.e first entering the number of instructions, next each instruction in one line. But if I paste a set of input lines and press enter then this code is reading one extra line input.
To be clear let me explain this with the example I tried:
input text:
6
+ 1
+ 10
-
+ 2
+ 1234
-
the expected output is:
10
1234
But the program is waiting to read input after printing 10 so the output looks like:
10
//waiting for input now if I enter some text let's say test and hit enter, then it's printing 1234.
1234
I wrote the last println statement to test whether or not I am reading input and the String str is printing -test
Can someone please explain why this behavior is occurring?
The nextLine() method of java.util.Scanner class advances this scanner past the current line and returns the input that was skipped. This function prints the rest of the current line, leaving out the line separator at the end.
If you are trying to paste a set of instructions, after each line of the set try to add "\n", otherwise it may think that the entire set of instructions is just one single line.
You can also do some testing of how the lines are perceived by using the hasNextLine() method.
you can checkout my code. Here, you can directly paste set of input all together and it will work fine:
public static void stackExample() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Stack<Integer> stack = new Stack<>();
int n = Integer.parseInt(br.readLine());
String str = "";
for (int i = 0; i < n; i++) {
str = br.readLine();
//This is for handling, if there is any extra newline or a space in input
if (str.isEmpty() || str.equals(" ")) {
i--;
continue;
}
if (str.charAt(0) == '+') {
stack.add(Integer.parseInt(str.substring(1).trim()));
} else {
System.out.println(stack.pop());
}
}
}

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).

Scanner object executes only one time in while loop

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();

Program only prints out second last letter. want the whole word backwards instead

import java.util.Scanner;
public class Project2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String word;
String c;
int x, count, count1;
System.out.println("Please enter a word:");
word=in.nextLine();
x=word.length();
for(count=0;count<x;count++) {
count1=x;
count1--;
c=word.substring((count1)-1,count1);
System.out.println(c);
}
}
}
All this program does is print out the second to last character of the word that the user enters. I'm confused as to why it is doing this and want to know how to print out the whole word backwards. Someone help please.
You don't need a loop to reverse a string.
Ref - StringBuilder#reverse
Scanner in = new Scanner(System.in);
System.out.println(new StringBuilder(in.nextLine()).reverse());
If you want to print characters in reverse, then forget the substring-ing.
String word = in.nextLine();
int x = word.length();
for(count = x - 1; count >= 0; count--) {
System.out.println(word.charAt(count));
}
Take count1=x; assignment out of the loop. Also make count--; after printing the letter.
You are correct up until x = word.length(). It is printing the second from last character because you keep setting the value of count1 to length of word and you substract it by 1. Therefore, it keeps referring to the second last character. To fix that, do the following instead:
count1=x;
for(count=0;count<x;count++) {
c=word.substring((count1)-1,count1);
System.out.println(c);
count1--;
}
Every time the loop is running, you are resetting the count1 value to x (count1=x). So c will always be the same value.
To make this work, try taking count1 = x out of the loop so that every time the loop is running, count1 value will be reduced as expected providing the required sub-string.
Into the loop for(count=0;count<x;count++)
Every loop you did the same thing
count1=x;
count1--;
c=word.substring((count1)-1,count1);
System.out.println(c);
This block has no relation with the loop!
Thats why you are getting the second last character!
To fix this:
Solution 1: (Just reverse the String)
word=in.nextLine();
System.out.println(new StringBuilder(word).reverse());
or Solution 2: (Using loop using your code)
x=word.length();
for(count= x-1; count >= 0; count--) {
c = word.substring((count)-1, count);
System.out.print(c);
}
If at all you want to do it the hard way by traversing, do the following changes.
for(count=x;count>=0;count--) {
System.out.println(word.substring(count - 1,count));
}
Update: You can use charAt#String to easily get the character at some position.
for(count=x-1;count>=0;count--) {
System.out.println(word.charAt(count));
}

Printing an input's digits each in a new line

First of all, i just started programming with Java so i'm really a noob :P
Ok so my instructor gave me an assignment which is to take an int input from the user and put each digit in a new line.
for example, if the user gave 12345, the program will give:
1
2
3
4
5
each number in a new line.
The statements i will be using is IF statement and the loops and operators ofcourse.
I thought about using the % operator inside the IF/WHILE but i have two issues. One is that i don't know the number of digits the user is inputting and since i can't use the .length statement i reached a dead end. second of all the console output will be 5 4 3 2 1 inversed.
So can anyone help me or give me any ideas?
import java.util.Scanner;
public class NewLineForDigit {
public static void main(String[] args) {
System.out.print("Please, enter any integer: ");
Scanner sc = new Scanner(System.in);
String intString = sc.next();
for (char digit : intString.toCharArray()) {
System.out.println(digit);
}
}
}
Given the assignment your instructor gave you, can you convert the int into a String? With the input as a String, you can use the length() String function as you had mentioned to iterate the number of characters in the input and use the built-in String function charAt() to get the index of character you want to print. Something like this:
String input = 12345 + "";
for(int i = 0; i < input.length(); i++)
System.out.println( input.charAt(i) );
How about using a Scanner to get the users input as an int and converting that int to a String using valueOf. Lastly loop over the String to get the individual digits converting them back to int's from char's :
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Please enter a Integer:");
int input = sc.nextInt();
String stringInput = String.valueOf(input);
for(int i = 0; i < stringInput.length(); i++) {
int j = Character.digit(stringInput.charAt(i), 10);
System.out.println(j);
}
}
}
Try it here!

Categories

Resources