Not asking for second input - java

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

Related

frequency of a letter in a string using arrays

In this program I have been having trouble to get the terminal window I suspect it might be a runtime error .I am using blue J btw. Also I dont understand why the code used this
f[ch-'A']++;
Please help out with a tracing for this program.
This is the code:
import java.util.*;
public class frequency
{
public static void main(String args[])
{
Scanner sc= new Scanner(System.in);
int f[]= new int[26];
System.out.println("enter a string");
String input = sc.nextLine();
input= input.toUpperCase();
for(int i=0; i<input.length();i++)
{
char ch=input.charAt(i);
if (Character.isLetter(ch))
f[ch-'A']++;
}
System.out.println("Characters Frequency");
for(int i=0;i<26;i++)
{
if( f[i]!=0)
{
System.out.println((char) (i+'A') + "\t\t" + f[i]);
}
}
}
}
Because it is converting the text to uppercase
input= input.toUpperCase();
each char can have the ascii value of A subtracted (see https://www.asciitable.com/) to obtain an index into the array.
'B' - 'A' == 1 etc
test
enter a string
stupid sod
Characters Frequency
D 2
I 1
O 1
P 1
S 2
T 1
U 1

Reading multiple inputs from Scanner

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

error: incompatible types: String cannot be converted to int

I'm very new to programming and very very new to Java, so I'm sure this question (and all my other mistakes) will be very obvious to anyone with experience. I clearly don't know what I'm doing.
My assignment was to convert Python code to Java. Below is my code.
My two error codes are:
Assignment1.java:37: error: incompatible types: String cannot be
converted to int
response = reader.nextLine();
Assignment1.java:38: error: incompatible types: int cannot be converted to String
num = Integer.parseInt(response);
For clarification, I'm using JGrasp, but willing to not.
import java.util.Scanner;
public class Assignment1 {
public static void main(String[] args) {
int num, response, min, max, range, sum, count, avg;
Scanner reader = new Scanner(System.in);
String reportTitle;
//title
System.out.println();
System.out.println("Enter a title for this report");
reportTitle = reader.nextLine();
System.out.println();
//data input
System.out.println("Enter a series of numebr, ending with a 0");
num = 0;
sum = 0;
response = 1;
count = 0;
max = 0;
min = 0;
range = 0;
while (true)
{
if (response < 1)
{
System.out.println("End of Data");
break;
}
System.out.println("Enter number => ");
response = reader.nextLine();
num = Integer.parseInt(response);
sum += num;
count += 1;
if (num>max)
{
max = num;
}
if (num<min)
{
min = num;
}
}
//crunch
avg = sum / count;
range = max - min;
//report
System.out.println();
System.out.println(reportTitle);
System.out.println();
System.out.println("Sum: => "+sum);
System.out.println("Average: => "+avg);
System.out.println("Smallest: => "+min);
System.out.println("Largest: => "+max);
System.out.println("Range: => "+range);
}
}
response is an int and the method nextLine() of Scanner returns... well, a line represented by a String. You cannot assign a String to an int - how would you do so? A String can be anything from "some text" to " a 5 0 ". How would you convert the first and/or the second one to an int?
What you probably wanted is:
System.out.println("Enter number => ");
response = reader.nextInt();
// notice this ^^^
instead of:
System.out.println("Enter number => ");
response = reader.nextLine();
// instead of this ^^^^
the nextInt() method expects a sequence of digits and/or characters that can represent a number, for example: 123, -50, 0 and so on...
However, you have to be aware of one significant issue - mixing nextLine() and nextInt() can lead to undesirable results. For example:
Scanner sc = new Scanner(System.in);
String s;
int a = sc.nextInt();
s = sc.nextLine();
System.out.println(s);
Will print nothing, because when inputting the number, you type for example 123 and hit enter, you additionally input a newline character. Then, nextLine() will fire and will scan every character up to the first enountered newline or end-of-file character which apparently is still there, unconsumed by nextInt(). To fix this and read more about it go here
To read an integer from a file you can simply use an example like this:
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
However, you dont give further information about your file structure so my advice is to look again in the documentation to find what best fits you.
You can find the documentation of scanner here.

This java program produce unwanted results

I wrote a program that read input and then print it out.
public class inverse {
public static void main (String arg[]) throws IOException {
int input1 = System.in.read();
System.out.println(input1);
String temp= Integer.toString(input1);
System.out.println(temp);
int[] numtoarray =new int[temp.length()];
System.out.println(temp.length());
for (int i=0 ;i<temp.length(); i++)
{numtoarray[i]= temp.charAt(i);
System.out.println(numtoarray[i]+"*");
}
}}
but here when I write 123456 it print 49. but it should print 123456. what cause this problem?
123456 is an integer, but System.in.read() reads the next byte as input so it will not read the integer as expected. Use the Scanner#nextInt() method to read an integer:
Scanner input = new Scanner(System.in);
int input1 = input.nextInt();
Your numtoarray array will also print the bytes, not the individual characters of the integer parsed as a string. To print the characters, change the type to a char[]:
char[] numtoarray = new char[temp.length()];
System.out.println(temp.length());
for (int i = 0; i < temp.length(); i++) {
numtoarray[i] = temp.charAt(i);
System.out.println(numtoarray[i] + "*");
}
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.
You can use Scanner instead
Here is the code
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
int input1 = in.nextInt();
System.out.println(input1);
String temp= Integer.toString(input1);
System.out.println(temp);
char[] numtoarray =new char[temp.length()];
System.out.println(temp.length());
for (int i=0 ;i<temp.length(); i++){
numtoarray[i]= temp.charAt(i);
System.out.println(numtoarray[i]+"*");
}
}
DEMO

Why is my for loop executing more than once for each time a value is inputted?

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

Categories