how to get the final output without pressing enter? - java

In the below code when i enter the input as***(i just don't enter the input one by one instead i copy and paste the entire input)***
4
101
1111
00110
111111
i am supposed to get
5
15
6
63
instead i get
5
15
6
and after i press enter here
i get the 63
import java.util.Scanner;
public class VonNeumanLovesBinary {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int no = scn.nextInt();
while (no > 0)
{
int binary = scn.nextInt();
int i = 0 ;
int sum = 0;
while(binary > 0 )
{
int digit = binary % 10;
sum += Math.pow(2,i) * digit ;
binary /= 10;
i++;
}
System.out.println(sum);
no--;
}
}
}
This code is written Intellij IDE.
Please help me out . this is the problem of the ide ?

Its not the fault of the IDE. It is how it deals with copy-pasting text into the console.
The text is handed over to the Java code as you paste it, line by line. Input is only handed over once you finish the line. The previous lines are all terminated already with a newline symbol but the last line is not.
So you have to either add a newline to the end of your copy-pasta or hit enter to produce one yourself. So before you terminate the last line, the last line is never handed over to Java but is still only in the console.
For example, if you copy pasta this instead:
4
101
1111
00110
111111
(note the last, empty line)
it will work as expected, since you finished the 111111 line, i.e. it is 111111\n and not just 111111.

Related

Processing IDE doesn't read data right from serial

I am trying to make an arduino project with arduino ide and processing ide.
I started doing a simple test to see the enviornment where I display the numbers 0,1..9 using arduino ide, but processing ide doesn't read it right for some reason and I can't figure out why, it reads weird numbers from serial like 10, 13, 53 and so on (only these numbers, nothing changes). Here is my processing code:
import processing.serial.*;
Serial port;
void setup() {
port = new Serial(this,"/dev/ttyUSB0",9600);
}
void draw() {
if(port.available() > 0) {
int info = port.read();
println(info);
println("===");
}
}
And here is my arduino code:
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
int deg = 0;
int data = 1;
for (deg = 0; deg < 10; deg++) {
Serial.println(deg);
delay(15);
delay(1000);
}
}
Also, the board and processing are using the same port /dev/ttyUSB0.
I am running all of this on Ubuntu 20.04. I tried to look on google but can't seem to find anything.
Thanks in advance, any tip is welcome.
Your are sending ASCII from Arduino and reading binary in your Processing IDE. Here is what your sender is doing:
for (deg = 0; deg < 10; deg++) {
Serial.println(deg);
...
}
Serial.println prints the value, meaning it's formatted for display. That means it's converted to ASCII. The output of this will be each number, in ASCII, followed by a new line (thus the 'ln' in the println function):
48 10 13 49 10 13 50 10 13 ... 57 10 13
For example, Serial.println(0) will yield 48 10 13 which is the ASCII code for 0 followed by the new line sequence 10 13 (CR and LF).
Your receiver is doing this:
int info = port.read();
println(info);
Which will read these values as integers and format those numbers as ASCII outputs with new lines. So you will see on your display:
48
10
13
...
The best way to solve this is to write binary data from Arduino instead of printing the data. On your Arduino, use Serial.write() instead:
for (deg = 0; deg < 10; deg++) {
Serial.write(deg);
...
}

How to add a variable to another variable that's already set

My homework is to create a program that takes a list of numbers and prints out the highest number divisible by four.
List would look like this:
12
16
87
58
25
73
86
36
79
40
12
89
32
Input should be:
40 because it is the highest number there divisible by four.
Here is my code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int saved = 0;
int saved2 = 0;
for (int i = scanner.nextInt(); i % 4 == 0; i = scanner.nextInt()) {
for (boolean bull = true; bull == true; bull ^= true) {
if (i > saved) {
saved -= saved2;
saved += i;
saved2 += i;
}
}
System.out.println(saved);
}
}
}
The input of my code is
12
16
I don't really understand why this is doing it, but it seems to me that I'm adding the variables wrong. The homework page on adding variables does not specify how to add variables to each other.
Does anyone have a tip to improve the code in anyway, or find a way to make a fix my code? Thank you.
welcome to Java.
First you are saying you got input, but that is output. Input is what you enter, and output is what you get printed.
Then there is a mistake in your for loops. You have too much going on in one place. By the logic which is implemented, your program will exit first level for loop whenever your entered value is not divisable by 4.
Read on for loops if you want to learn more https://www.learnjavaonline.org/en/Loops.
I recommend to start from while loops instead. The logic whould be this:
1. create variable to hold the correct answer saved
2. create another one to hold the value read from console i
3. start the while loop with condition i = scanner.nextInt()
3.1 check if the value just entered i is divisable by 4
3.2 if it is, then compare if it's larger than the one was saved before (initially saved value will be 0)
3.3 if it is larger, then assign the read value i to the saved
4. At the end of the loop, you will have the highest number divisable by four in your saved variable. Print it.
I will provide some help, according to
How do I ask and answer homework questions?
for (int i = scanner.nextInt(); i % 4 == 0;i = scanner.nextInt())
This only reads as long as ALL inputs are divisible by 4, that is why it ends at 16, because 87 is not divisible by 4.
for (boolean bull = true; bull == true ;bull ^= true)
This needs explanation by you, but I am pretty sure that it unconditionally executes the body of the inner loop exactly once. (Not 100% sure, because the representation of true and false could be weird in your machine. Should 0 be the representation of true, i.e. really weird, then it is an endless loop, which does not match the output you describe...)
System.out.println(saved);
This executes exactly once per input, except the last one, which is not a multiple of 4.
The value of saved is identical to input, as long as it is increasing.
These hints explain the unexpected output.
If you inspect the details of what the problem is, you should be able to improve your coding attempt.
This is how I super-quickly fixed in your code.
Note that there are no statements about the possible minimum value and about how do you stop the input. Therefore the solution is pretty-straightforward, it just reads the input until integers are present there.
This article may be useful about handling the input from the Scanner.
I hope the comments in the code will help. Add comments if there are any questions. Good luck!
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int currentMax = Integer.MIN_VALUE; // you may set negative or 0 if you know that all the input is positive
// int saved2 = 0; // no need for this variable
while (scanner.hasNextInt()) { // you can make a better input handling, especially if you know when it should end the input. Now it will end on any non-integer input line
int i = scanner.nextInt();
// for (int i = scanner.nextInt(); i % 4 == 0; i = scanner.nextInt()) {
// for (boolean bull = true; bull == true; bull ^= true) {
if (((i % 4) == 0) && (i > currentMax)) {
currentMax = i;
// saved -= saved2;
// saved += i;
// saved2 += i;
// }
}
}
System.out.println(currentMax); // moved out of "for" or "while" cycles. Print the value after the input has ended.
}
}

Java program involving [closed]

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
I am trying to write the following program sequence.
The first three numbers in the sequence are 1, 1, 2. Every other number in the sequence is the sum of the three previous numbers. The program should prompt the user to enter a limit; the program will stop when the current number in the sequence is greater than or equal to this limit.
For example if I write the limit being 123 I should get: 1 1 2 4 7 13 24 44 81
I tried the following:
import jpb.*;
public class XiaolinSequence {
public static void main(String[] args) {
SimpleIO.prompt("Enter a limit on the largest number to be displayed:");
String userInput = SimpleIO.readLine();
int counter = Integer.parseInt(userInput);
int older = 1;
int old = 1;
int current = 2;
while (current < counter) {
int nextNumber = older + old + current;
older = old;
old = current;
current = nextNumber;
System.out.println(nextNumber);
}
}
}
But I am having trouble getting the sequence to print out.
You need to change how you print things.
The missing 1 1 2 are never printed because they are never stored in nextnumber, the only variable you ever print.
You will get an additional 149 because you print nextnumber without checking it its value is greater than the limit.
For me the output of the following code is 1 1 2 4 7 13 24 44 81 all on new lines.
int counter=123; // replaced IO code so I did not have to download the jar.
int older=1;
int old =1;
int current=2;
System.out.println(older); // prints the first 1
System.out.println(old); // prints the second 1
System.out.println(current); // prints the 2
while(current<counter){
int nextnumber=older+old+current;
older=old;
old=current;
current=nextnumber;
if(nextnumber <= counter)
{
System.out.println(nextnumber);
}
}
Ok since people bashed me for your SimpleIO, use whatever you want to read the input. Instead, I'm going to point out a logic flaw in your code.
For the program to function correctly, you need to print out older instead of current, like so:
while (older < counter)
{
System.out.println(older);
final int nextnumber = older + old + current;
older = old;
old = current;
current = nextnumber;
}
It works just fine.
There is no such thing as SimpleIO in java.lang.
You may want to replace String userInput = SimpleIO.readLine() with
System.out.print("Enter limit: ");
Scanner in = new Scanner(System.in);
String userInput = in.next();
then the code will work.
Oh and by the way, don't forget to print out 1 1 2 before you start the loop.

Maintaining proper spacing in Java

I made a program that should output 2 lists of strings (anywhere between 2 and 5) at the end of the line, I want to print an int in brackets.
I am having trouble right justifying the int and the brackets.
All of the printf formatting does not help with moving the int and its surrounding brackets!
while (dealerPoints < 17 && playerBust == false) {
System.out.printf("\nDealer has less than 17. He hits...\n");
int nextDealerCard = dealCard();
dealerPoints += cardValue(nextDealerCard);
dealerHand += faceCard(nextDealerCard);
System.out.printf("Dealer: %s\t[%d]\n", dealerHand, dealerPoints);
System.out.printf("Player: %s\t[%d]\n", playerHand, playerPoints);
}
When there are 4 strings on one line and only 2 on the other, the int and brackets don't align with each other (the one after 4 strings, gets tabbed over too far)
System.out.printf("Dealer: %s\t[%10d]\n", "lala", 22222);
System.out.printf("Player: %s\t[%10d]\n", "hoho", 33);
Outputs:
Dealer: lala [ 22222]
Player: hoho [ 33]
is this what you want?
If you want to right justify, you can either
- write the output in a file as a CSV and open it in an excel like program
- create a utility class that will make any input string a constant length:
public static String fixedCharCount( String input, int length ) {
int spacesToAdd = length - input.lengh();
StringBuffer buff = new StringBuffer(input);
for( int i=0; i<spacesToAdd; i++) {
buff.append(" ");
}
return buff.toString();
}
You can also loop on all your data befor display to see what is the longest String in your table and adapt the length to it (the code is not complete: you must check 'spacesToAdd' is positive.

Java File IO scan into variables

this is basically my first true Java assignment and I've hit a brick wall. I basically wrote my entire project as if the user were to input the information into the program. upon rereading the assignment I saw that we are to input the info from a .txt file in the following format:
1.17 12 15( and then sort them)
7 54 9873 1867 4425 878 365 783 (where the first number n indicates how many n will folow)
4 (flyods triangle problem)
20 (fizz buzz problem)
I have all of the code written to solve these parts of the project but am completely stuck on how to implement the numbers from the .txt file. I am not asking for code merely some advice on how you guys might go about doing so/
import java.util.Arrays;
import java.util.Scanner;
public class FunTime {
public static void main(String args[])
{
int n, num = 1, c, d;
Scanner in = new Scanner(System.in);
n = in.nextInt();
for ( c = 1 ; c <= n ; c++ )
{
for ( d = 1 ; d <= c ; d++ )
{
System.out.print(num+" ");
num++;
}
System.out.println();
}
Fortunately, reading from a file is exactly like reading from the terminal. Instead of reading from System.in, read from a file that you open with something like FileInputStream.

Categories

Resources