Multiline input in Java - java

I am trying to read an input like this:
5 3 3
1 2 3 4 5
5 4 3 2 1
When I use the scanner and try something like this:
Scanner sc = new Scanner(System.in);
int n, x, y;
String[] temp = sc.nextLine().split(" ");
n = Integer.parseInt(temp[0]);
x = Integer.parseInt(temp[1]);
y = Integer.parseInt(temp[2]);
int[] a, b;
a = b = new int[n];
String[] t = sc.nextLine().split(" ");
for(int i = 0; i < n; i++){
a[i] = Integer.parseInt(t[i]);
}
String[] f = sc.nextLine().split(" ");
for(int i = 0; i < n; i++){
b[i] = Integer.parseInt(f[i]);
}
This just prints that the arrays 'a' and 'b' are same;
[5, 4, 3, 2, 1]
[5, 4, 3, 2, 1]
12
How can I read this input?

The problem with your code is not how you read the input, but this line here:
a = b = new int[n];
In this line, you set a and b to the same new int array. You did create a new array here, but you only created one. Both a and b refer to that same one. So when you are doing b[i] = ..., you are in fact overwriting the values you've just written to it in the first loop.
You should create two arrays:
a = new int[n];
b = new int[n];
Note that another way to read the input is to use nextInt, but your way is okay too.
Scanner sc = new Scanner(System.in);
int n, x, y;
n = sc.nextInt();
x = sc.nextInt();
y = sc.nextInt();
int[] a, b;
a = new int[n];
b = new int[n];
for(int i = 0; i < n; i++){
a[i] = sc.nextInt();
}
for(int i = 0; i < n; i++){
b[i] = sc.nextInt();
}

This is causing the problem.
a = b = new int[n];
Both a, b are referencing the same array object. Hence, the later input is overriding the previous input. Change this to:
a = new int[n];
b = new int[n];

Related

Bubblesort random Array Java

I'm very new to java and have been playing around with sorting algorithms. I have the following code working for a set array. I was just wondering what I'd need to change to get it to sort arrays of randoms lengths and integers. I guess the answer is pretty obvious any help is appreciated!
public static void main(String[] args) {
int number[]={8,5,3,2,9};
int temp;
boolean fixed=false;
while(fixed==false){
fixed=true;
for(int i=0; i<number.length-1 ; i++){
if(number[i] > number[i+1]){
temp = number[i+1];
number[i+1]=number[i];
number[i]=temp;
fixed=false;
}
}
}
for(int i=0; i<number.length; i++)
System.out.println(number[i]);
}
}
I mean, your algorithm would work regardless of the array's length. About how to generate such arrays, you could do this:
int n = Math.random()*10000 + 1; //so its never 0.
int number[] = new int[n];
for(int i=0;i<n;i++) number[i]=Math.random()*10000;
Everything else stays the same :).
EDIT: You commented on the question that you'd rather generate the array by taking an input from the keyboard. You can do that by using a scanner.
Scanner scanIn = new Scanner(System.in);
do{
int n = scanIn.nextInt();
} while (n<1);
int number[] = new int[n];
for(int i=0;i<n;i++) number[i] = scanIn.nextInt();
scanIn.close();
What you are looking for is probably a method to extract your bubblesort to. Please note that this method changes the input array and does not return a new array.
private static void bubblesort(int[] array) {
int temp;
boolean fixed = false;
while (!fixed) {
fixed = true;
for (int i = 0; i < array.length - 1; i++) {
if (array[i] > array[i + 1]) {
temp = array[i + 1];
array[i + 1] = array[i];
array[i] = temp;
fixed = false;
}
}
}
}
You can then call it using different approaches.
Fixed size array:
// fixed size array
int number[] = {8, 5, 3, 2, 9};
bubblesort(number);
System.out.println(Arrays.toString(number));
Read numbers from System.in.
// read from sys.in like "2 6 4"
Scanner s = new Scanner(System.in);
String line = s.nextLine();
int[] parsedInts = Arrays.stream(line.split("\\s+")).mapToInt(Integer::parseInt).toArray();
bubblesort(parsedInts);
System.out.println(Arrays.toString(parsedInts));
You can the use Scanner Class in java and need to import java.util.Scanner class
Scanner sc = new Scanner(System.in);
System.out.println("Enter the array length :");
int n = sc.nextInt();
int number[] = new int[n];
System.out.println("Enter the numbers :");
for(int i = 0; i < number.length; i++) {
number[i] = sc.nextInt();
}

Extract each seperate number from string

I have this as an input "1 2 3 4 5" and I want to have it like this
int[] numbers = new int[5];
number[0] = 1;
number[1] = 2;
number[2] = 3;
number[3] = 4;
number[4] = 5;
So how can I extract each number from a string and put it in an int array?
ConsoleIO io = new ConsoleIO();
int[] numbers = new int[5];
io.writeOutput("Type in 5 numbers");
String input = io.readInput();
// If input is longer than 1 character for example, "1 2 3 4 5"
if(input.length() > 1) {
System.out.println(input.length());
for(int y = 0; y < io.readInput().length(); y++) {
numbers[y] = Integer.parseInt(io.readInput().substring(y, io.readInput().indexOf(" ")));
}
return;
}
// If input is one number for example, "1"
else {
for(int i = 0; i < numbers.length; i++) {
numbers[i] = Integer.parseInt(io.readInput());
}
}
The else works, so if I enter one number and press enter and then the next one, it's all good. But if I have a sequence of numbers with a space in between ("1 2 3 4 5") the program just breaks.
String input = io.readInput();
int[] arr = new int[5];
if(input.length() >= 5){
String[] c = input.split(" ");
for(int i = 0; i < c.length(); i++){
arr[i] = Integer.parseInt(c[i]);
}
}
Why not use a Scanner and then split and parse?
Scanner in = new Scanner(System.in);
String[] nums = in.nextLine().split(" ");
for(int i = 0; i <=5; i++) {
numbers[i] = Integer.parseInt(nums[i]);
}
Assume your input is always numbers with a space between each other (or just one number), in Java 8 you can work in this way:
String[] splits = input.split(" ");
int[] result = Arrays.stream(splits).mapToInt(Integer::parseInt).toArray();
import java.util.*;
public class Solution {
public static void main(String []args) {
Scanner in = new Scanner(System.in);
String[] nums = in.nextLine().split(" ");
int[] numbers = new int[5];
for(int i = 0; i <5; i++) {
numbers[i] = Integer.parseInt(nums[i]);
System.out.println(numbers[i]);
}
}
}

Create multiple arrays using a for loop

I would like to make a program where the user can input the number of variables and fill every variable with certain values. For example, the User inputs that he/she wants to make 10 arrays, then the User inputs that the first array should have 5 elements and the User fills that array with values, then the User wants the second array to have 4 elements and does the same and so on.
This is the code I was using, but it doesn't work:
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.println("Enter the numbers of variables: ");
int i = s.nextInt();
for(int j = 0;j < i;j++){
int[] var = new int[j];
System.out.println("Enter the number of values: ");
int p = s.nextInt();
for(int q = 0;q < p;p++){
int n = s.nextInt();
var[q] = n;
}
}
}
And how could I compare these arrays that the user inputs?
The problem is that each time you are creating the array.
try this:
Scanner s = new Scanner(System.in);
System.out.println("Enter the numbers of variables: ");
int i = s.nextInt();
int[][] var = new int[i][];
for(int j = 0;j < i;j++){
System.out.println("Enter the number of values: ");
int p = s.nextInt();
var[j] = new int[p];
for(int q = 0;q < p;p++){
int n = s.nextInt();
var[j][q] = n;
}
}
Instead of creating a one dimensional array, you create a jagged array. Essentially, a 2d array is an array of arrays. that way the user inputs the number of arrays (i) and then continues to fill the arrays.
To check whether two collections have no commons values, you can use
Collections.disjoint();
For other operations, you can look here
This should work (with bidimensionnal array)
public static void main(String[] args){
Scanner s = new Scanner(System.in);
System.out.println("Enter the numbers of variables: ");
int i = s.nextInt();
int[][] var = new int[i][];
for(int j = 0;j < i;j++){
System.out.println("Enter the number of values: ");
int p = s.nextInt();
var[j] = new int[p];
for(int q = 0;q < p;q++){
int n = s.nextInt();
var[j][q] = n;
}
}
}
You have to replace the incrementation in the second loop too ("q++" instead of "p++")
This should work and solve their first point
Scanner s = new Scanner(System.in);
System.out.println("Enter the numbers of variables: ");
int i = s.nextInt();
int[][] var = new int[i][];
for(int j = 0;j < i;j++){
System.out.println("Enter the number of values: ");
int p = s.nextInt();
while (p>0)
{
var[j] = new int[p];
for(int q=0;q < p;q++){
System.out.println("Value number : " +(q+1) + " For Array Number "+ (j+1));
int n = s.nextInt();
var[j][q] = n;
}
p-=1;
}
}

if condition get skipped for calculating average in a loop based on some condition

I want to take the average while value in column A is lower than its next value and value in column B is the same as its next value. The average is taken from column C value based on column A value as column C index. Following is the data sample:
columnA,B,C
0,0,0.36
1,0,0.23
2,0,0.14
3,1,0.41
4,1,0.44
5,2,0.16
6,2,0.03
7,2,0.09
Following is my current code:
import java.io.*;
import java.util.*;
public class dtw_post {
public static void main(String[] args) throws Exception {
//Scanner scan = new Scanner(System.in);
int N = 655;
int x = 655;
File file = new File("box_raw.txt");
Scanner scannerFile = new Scanner(file);
while(scannerFile.hasNextLine()){
String line = scannerFile.nextLine();
String[] lineVector = line.split(",");
int a[] = new int[N];
int b[] = new int[N];
double c[] = new double[x];
for(int i = 0; i<N; i++)
{
a[i]=Integer.parseInt(lineVector[0]);
b[i]=Integer.parseInt(lineVector[1]);
c[i]=Double.parseDouble(lineVector[2]);
}
System.out.println((dtw_post.lookup(a,b,c)));}
}
static String lookup (int[] a, int[] b, double[] c){
int j=0; int i=0;
String[] final_result = new String[c.length];
while(i < a.length-1){
if (a[i] < a[i+1] && b[i] == b[i+1]) {
double[] d = {c[a[i]],c[a[i+1]]};
double sum = 0;
int number = 0;
for (double val : d) {
++number;
sum += val;
}
double e = sum/number;
final_result[i] = String.valueOf(e);
i++;
}
else {
final_result[i] = String.valueOf(c[a[i]]);
i++;
}
}
String result = final_result[j]; j++;
return result;
}
}
I expect it to output 0.243 in the first line as the average of 0.36,0.23,and 0.14. I figure that the problem is in the if condition in the lookup method. It seems to skip the if and run the else condition only. My current code output column C exactly as it is. What went wrong in my if condition loop? Thank you for your time.
The first issue is you are parsing the file wrong. You are parsing the file line by line in a while loop. But you are creating new a, b and c arrays for each line. Move the initialization out of the for loop :
public static void main(String[] args) throws Exception {
//Scanner scan = new Scanner(System.in);
int N = 655;
int x = 655;
int a[] = new int[N];
int b[] = new int[N];
double c[] = new double[x];
int i = 0;
File file = new File("box_raw.txt");
Scanner scannerFile = new Scanner(file);
while (scannerFile.hasNextLine()) {
String line = scannerFile.nextLine();
String[] lineVector = line.split(",");
a[i] = Integer.parseInt(lineVector[0]);
b[i] = Integer.parseInt(lineVector[1]);
c[i] = Double.parseDouble(lineVector[2]);
++i;
}
System.out.println((dtw_post.lookup(a, b, c)));
}
Based on that you will only get an average of two consecutive values. You also need to rethink the lookup function. Increase the sum until the value in b changes and then calculate the average and print it. E.g
static String lookup(int[] a, int[] b, double[] c) {
String result = "";
double sum = c[a[0]];
int consecutive = 1;
for (int i = 1; i < a.length - 1; ++i) {
if (a[i - 1] < a[i] && b[i - 1] == b[i]) {
sum += c[a[i]];
++consecutive;
} else {
result += String.valueOf(sum / consecutive) + '\n';
sum = c[a[i]];
consecutive = 1;
}
}
return result;
}
Ad a side note, you should also consider StringBuilder for concatenating strings in a loop
In your if condition you required that a[i] is less than a[i+1], shouldn't it be a[i] greater than a[i+1]?
So the if should be:
if(a[i]>a[i+1] && b[i]==b[i+1]){
....
You are processing only one line of the file at a time. The loop reads one line from the file and splits it to get values for a,b,c. Then it copies these values into EVERY cell in the corresponding arrays, and then calls lookup. Since every value of a is the same, if statement is never true.
What you want to do is fill in each successive cell in a,b,c with the next line read, and call lookup outside the while loop. What I think you want is:
public static void main(String[] args) throws Exception {
//Scanner scan = new Scanner(System.in);
int N = 655;
File file = new File("box_raw.txt");
Scanner scannerFile = new Scanner(file);
int a[] = new int[N];
int b[] = new int[N];
double c[] = new double[N];
int i = 0;
while(scannerFile.hasNextLine()){
String line = scannerFile.nextLine();
String[] lineVector = line.split(",");
a[i]=Integer.parseInt(lineVector[0]);
b[i]=Integer.parseInt(lineVector[1]);
c[i]=Double.parseDouble(lineVector[2]);
i++;
}
System.out.println((dtw_post.lookup(a,b,c)));
}

converting an arraylist(integer) to an integer array

I've tried couple of things to make this code work, but it didn't.
my goal is to instantiate nums[] with numbers {0, 1, 2, .... n-1}. nums has no size, so I used list that instantiate nums with zeros. Keep in mind that the result must be an array (nums).
int nums[] = {}; int n = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number:");
n = scanner.nextInt();
ArrayList<Integer> listNum = new ArrayList<Integer>();
nums = new int[listNum.size()];//instantiate nums with zeros
//nums = listNum.toArray(nums);
for (int i =0; i < n; i++){
nums[i] = i;
}
When you're writing this :
ArrayList<Integer> listNum = new ArrayList<Integer>();
nums = new int[listNum.size()];//instantiate nums with zeros
listnum has a size of 0, so nums won't be initialized as you want.
Why not just do :
nums = new int[n];
?
Array's are fixed in size.
nums = new int[listNum.size()];
That never works. You are initializing your array with zero elements. Once you declare the array size, you can't change that back.
What you are looking for is
int nums[] = {}; int n = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number:");
n = scanner.nextInt();
nums = new int[n];//instantiate nums with entered size
for (int i =0; i < n; i++){
nums[i] = i;
}
Just get rid of that ArrayList since you are know the size n
You don't need an ArrayList - if you take the input of n from the command line, you could just use it to initialize the array:
nums = new int[n];
for (int i =0; i < n; i++){
nums[i] = i;
}

Categories