reading the file from right side in java - java

Suppose the file sample.txt content is:
1 casual 1 3 5 5
2 casual 5 2 5 3
3 casual 1 5 4 3
4 dress 4 5 4 4
5 athletic 2 4 5 2
Now, what i want is to take the last four numbers and possibly multiply each with four more numbers that will be taken from the user as:
Take the last four digits of the first line i.e. 1 3 5 5
then:
input1x1 + input2x3 + input3x5+ input4x5 = result.
Can anyone help me on how to achieve this, this is the code i have written till now which can read the file and then convert into list. :
import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args) throws FileNotFoundException{
FileReader n = new FileReader("sample.txt");
Scanner in = new Scanner(n);
ArrayList<String> lines = new ArrayList<String>();
while (in.hasNext()) {
lines.add(in.nextLine());
}
in.close();
System.out.println(lines.get(1));
// for (int i = 0; i<lines.size()-1; i++) {
// System.out.println(lines.get(i));
// }
}
}

for(int i = 0; i < lines.size() - 1; i++) {
String line = lines.get(i);
String[] parts = line.split(" ");
int result = 0;
result += Integer.parseInt(parts[2]) * 1;
result += Integer.parseInt(parts[3]) * 3;
result += Integer.parseInt(parts[4]) * 5;
result += Integer.parseInt(parts[5]) * 5;
System.out.println(line + " -> " + result);
}

After you run your above code, this gets 4 integers from user and multiplies them with your files numbers
Scanner sc = new Scanner(System.in);
for(int i = 0; i < lines.size(); i++) {
String[] number = lines.get(i).split(" ");
int result = 0;
for (int x=2;x<=5;x++) {
result += Integer.parseInt(number[x]) * sc.nextInt();
}
System.out.println(result);
}

Related

Selection Sort displaying each Pass

So my Professor gave us an activity where we input the amount of array and its value. Then Selection sort will be implemented and will display each pass. I manage to do the input part but only managed to display the unsorted and sorted output. I've been wracking my brains on how to show the input of each pass but I always come up short. I saw a code in C/C++ but I don't know how to read the language well enough to understand the code.
This is what the expected output:
Input a number: 5
a[0]: 5
a[1]: 4
a[2]: 2
a[3]: 8
a[4]: 10
UnSorted Array: 5 4 2 8 10
1st Pass: 5 4 2 8 10
2nd Pass: 5 4 2 8 10
3rd Pass: 2 4 5 8 10
Sorted Array Values :2 4 5 8 10
And here's my current output:
Input a number: 5
a[0]: 5
a[1]: 4
a[2]: 2
a[3]: 8
a[4]: 10
UnSorted Array: 5 4 2 8 10
Sorted Array Values: 2 4 5 8 10
This is my code:
public static void main(String[] args) {
// TODO Auto-generated method stub
/*
* input number of array
* display array
* 1st pass
* 2nd pass
* 3rd
* 4th
* 5th...
*/
Scanner ss = new Scanner(System.in);
int a, j, temp;
int arr[] = new int[50];
//input number of array
System.out.print("Input a number: ");
int num=ss.nextInt();
System.out.print("");
//display array
for (a = 0; a < num; a++) {
System.out.print("a[" + a + "]: ");
arr[a] = ss.nextInt();
}
//Unsorted Value
System.out.print("UnSorted Array: ");
for (a = 0; a < num; a++) {
System.out.print(arr[a] + " ");
}
System.out.println();
for (a = 0; a < num; a++) {
for(j = a + 1; j < num; j++) {
if(arr[a] > arr[j]) {
temp = arr[a];
arr[a] = arr[j];
arr[j] = temp;
}
}
}
//Passes
//Sorted Value
System.out.print("Sorted Array Values :");
for (a = 0; a < num; a++) {
System.out.print(arr[a] + " ");
}
}

Error when picking out unique numbers in an array

This is a problem in my textbook for my Java class where the user enters 10 integers. The program is supposed to read all integers and only display the unique numbers (not duplicated) as the output. I am having trouble understanding why my output is not picking up the last unique value in the array (5). Can anyone give some insight to this issue? Any help would be appreciated. (Since we are in the early stages of the class and understanding the language, our assignment is to complete this using a nested loop.)
-The output is:
Enter 10 numbers: 1 2 3 2 1 6 3 4 5 2
The number of distinct numbers is 5
The distinct numbers are: 1 2 3 6 4
-When it should be:
Enter 10 numbers: 1 2 3 2 1 6 3 4 5 2
The number of distinct numbers is 6
The distinct numbers are: 1 2 3 6 4 5
public class ch7e5{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter 10 numbers: ");
int[] numberArray = new int[10];
//create array for all numbers
int[] distinctArray = new int[10];
//create array for distinct numbers
int distinct = 0;
for (int i = 0; i < 10; i++)
numberArray[i] = input.nextInt();
distinctArray[0] = numberArray[0];
//first value will be distinct
for (int i = 1; i < numberArray.length; i++) {
//loop to go through remaining values in numberArray
boolean exists = false;
//create boolean
for (int j = 0; j < numberArray.length; j++) {
//loop to check if value exists already in distinctArray
if (numberArray[i] == distinctArray[j]) {
exists = true;
break;
//break out of inner loop
}
}
if (exists == false) {
//if value is unique then add it to the distinct array
distinct++;
distinctArray[distinct] = distinctArray[i];
}
}
//}
System.out.println("The number of distinct numbers is " + distinct);
System.out.print("The distinct numbers are: ");
for (int k = 0; k < distinct; k++)
System.out.print(distinctArray[k] + " ");
}
}```
There are 3 distinct numbers, 1, 2, and 3 are not any of them as they appear twice. The output should be 6 4 5. I'm not sure how you got 5 distinct numbers here, maybe you inputted them wrong? I would try not using a scanner at first and try putting the numbers in the array manually. Additionally, I would create a boolean array length 10 starting all true to record if numbers are distinct. If a number appears twice, the corresponding boolean in the array will be false. I will update this with code once i have written it.
EDIT: apparently having a duplicate does not delete it from the distinct list. If this is the case, please elaborate on the title.
Here is my code:
public class Main {
public static void main(String[] args) {
int inputs = 3;
int[] numberArray = new int[inputs];
int distinct = 0;
boolean[] mirror = new boolean[inputs];
//just setting up arrays
for(int i = 0; i < numberArray.length; i++) {
//numberArray[i] = i;
mirror[i] = true;
}
numberArray[0] = 1;
//finds out what numbers are not distinct
for (int x = 0; x < numberArray.length; x++) {
for (int y = 0; y < numberArray.length; y++) {
System.out.println("x is " + x);
System.out.println("y is " + y);
if(numberArray[x] == numberArray[y] && x != y) {
System.out.println(numberArray[x] + " is not distinct");
mirror[x] = false;//if current position in array matches any other position, number is not distinct
}
}
}
//calculates how many are distinct
for(int j = 0; j < inputs; j++) {
if(mirror[j]) {distinct++;}
}
//outputs text
System.out.println("The number of distinct numbers is " + distinct);
System.out.print("The distinct numbers are: ");
for(int k = 0; k < inputs; k++){
if(mirror[k]) {System.out.print(numberArray[k] + " ");}
}
}
}
The error was here
distinct++;
distinctArray[distinct] = distinctArray[i];
1, you should increment distinct after adding a number to distinctArray, and 2, you should have done distinctArray[distinct] = numberArray[i]. Right now, you're just putting what is possibly a 0 into distinctArray[distinct].
A shorter way to do it would be this
int[] distinctArray = Arrays.stream(numberArray).distinct().toArray();
System.out.println("The number of distinct numbers is " + distinctArray.length);
System.out.print("The distinct numbers are: ");
for (int d : distinctArray) System.out.print(d + " ");
Output:
Enter 10 numbers: 1 2 3 2 1 6 3 4 5 2
The number of distinct numbers is 6
The distinct numbers are: 1 2 3 6 4 5

Print a given number pattern from user input using nested for loop

I am new to programming. Am currently learning Java, on nested loop now, and got stuck.
So what I want to do is to write a program that takes an integer from user and
print lines, for example if user input was 4 then the result should be like:
1
1 2
1 2 3
1 2 3 4
Here is my code so far:
import java.util.Scanner;
public class Hello {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter number of rows:");
int number = input.nextInt();
for (int i = 1; i <= number; i++) {
System.out.println(i);
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
}
}
}
But it prints one extra line at the end, like:
1
1 2
1 2 3
1 2 3 4
1 2 3 4
And it is hard for me to figure out why.
I guess it is my first for loop but I don't know how to fix the for loop to get the result I want.
Any help will be appreciated. Thanks!
Don't print anything from the outer loop, only new line
for (int i = 1; i <= number; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
Output
1
1 2
1 2 3
1 2 3 4
To avoid the trailing spaces of the other answers,
rather than printing i at the start of the loop, print 1.
Then start the inner loop from 2 and print a space before each value. And print a new line after the inner loop.
for (int i = 1; i <= number; i++) {
System.out.print("1");
for (int j = 2; j <= i; j++) {
System.out.print(" " + j);
}
System.out.println();
}
Prints:
1
1 2
1 2 3
1 2 3 4
The problem is printing a newline and i at the same time... just take care of the new line after your for loop. The inner loop can handle all the prints.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter number of rows:");
int number = input.nextInt();
for (int i = 1; i <= number; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
Let's us dry run it
at first you print
1
then newline
then j goes from 1 to 1 nut no newline now 2 is printed by i now newline
so result 1 2
again j goes like 1 , 2 but no newline so again 3 is printed by i then newline
so result 1 2 3
again j goes like 1 , 2, 3, but no newline so again 4 is printed by i then newline
so result 1 2 3 4
again j goes like 1 , 2, 3, 4 // this one is the extra line

Java print multiple lines after reading multiple lines

(It's my homework task. So I can't make any changes to the task like changing the rules of input.)
I need to calculate
a^m mod n
and print out the result. (I've already figured out how to code the calculation.)
But the question said there'll be multiple lines of input:
IN:
12 5 47
2 4 89
29 5 54
and need to print all the results together after reading all the lines of input. (You can't print the results right after one line of input.)
OUT:
14
16
5
The code I've tried so far:
import java.util.Scanner;
public class mod {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int count = 0;
while (input.hasNextLine()){
count++;
}
int[] array = new int[count];
for (int i = 0; i < count; i ++){
int a = input.nextInt();
int m = input.nextInt();
int n = input.nextInt();
int result = (int)((Math.pow(a, m)) % n);
array[i] = result;
}
for (int x : array){
System.out.println(x);
}
}
}
I tried to count the lines of input and build an array of that size to store the results.
But it seems my code fail to detect the end of input and keep looping.
You can store the user's input in the initial loop with a List<String>, I would suggest terminating the loop on an empty String and only adding lines that match the three numbers separated by whitespace characters. Also, I would print the result in the second loop. Then you don't need a result array. I would also prefer formatted io (i.e. System.out.printf). Like,
Scanner input = new Scanner(System.in);
List<String> lines = new ArrayList<>();
while (input.hasNextLine()) {
String line = input.nextLine();
if (line.isEmpty()) {
break;
} else if (line.matches("\\d+\\s+\\d+\\s+\\d+")) {
lines.add(line);
}
}
int count = lines.size();
for (int i = 0; i < count; i++) {
String[] tokens = lines.get(i).split("\\s+");
int a = Integer.parseInt(tokens[0]), m = Integer.parseInt(tokens[1]),
n = Integer.parseInt(tokens[2]);
int result = (int) ((Math.pow(a, m)) % n);
System.out.printf("(%d ^ %d) %% %d = %d%n", a, m, n, result);
}
I tested with your provided input,
12 5 47
2 4 89
29 5 54
(12 ^ 5) % 47 = 14
(2 ^ 4) % 89 = 16
(29 ^ 5) % 54 = 5

My logical program is not giving the correct output?

Question:
The Utopian tree goes through 2 cycles of growth every year. The first growth cycle occurs during the spring, when it doubles in height. The second growth cycle occurs during the summer, when its height increases by 1 meter.
Now, a new Utopian tree sapling is planted at the onset of the spring. Its height is 1 meter. Can you find the height of the tree after N growth cycles?
Input Format
The first line contains an integer, T, the number of test cases.
T lines follow. Each line contains an integer, N, that denotes the number of cycles for that test case.
Constraints
1 <= T <= 10
0 <= N <= 60
Output Format
For each test case, print the height of the Utopian tree after N cycles.
//FINALLY, HOPE so .. WHAT QUESTION IS SAYING..
INITIALLY VALUE IS 1 .. IF SPRING OCCURS.. IT'S VALUE WILL BE DOUBLED.. THAT MEANS .. IT WILL BE MULTIPLIED BY 2.. BUT IF SUMMER OCCUR IT'S VALUE WILL BE ADDED BY 1...
If i give input:
2 //here 2 is the number of question..
0
1
So, Output must be:
1
2
Another example,
sample of output:
2
3
4
So, Sample of input will be:
6
7
HOPE SO.. YOU UNDERSTAND WHAT QUESTION IS ASKING, HERE NOW WE HAVE TO MAKE A PROGRAM INTO JAVA....
Okay as further i made a program for this..
package com.logical03;
import java.util.Scanner;
public class MainProgram{
public static void main(String[] args){
int num=1;
int[] array=new int[100];
Scanner in=new Scanner(System.in);
System.out.println("Enter the number of Questions: ");
int n_Elements=in.nextInt();
System.out.println("Enter the values now: ");
for(int i=1; i<=n_Elements; i++){
array[i]=in.nextInt();
}
for(int i=1; i<=n_Elements; i++){
if(array[i]==0){
System.out.println("\n1");
}
else{
for(int j=1; j<=array[i]; j++){
if(j%2!=0){
num=num*2;
}
else{
num=num+1;
}
}
System.out.println(num);
}
}
}
}
As i run into here .. it adds the second number of question into my output.. Suppose..
If i give input as:
2
3
4
So, output must suppose to be:
6
7
Which is correct!!
But My program gives the output as:
6
27 //which is incorrect..becoz it adds the sum of above number :(
Mistake - int num = 1; should be declared in inside parent loop to refresh it's value.
public static void main(String[] args) {
int[] array = new int[100];
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of Questions: ");
int n_Elements = in.nextInt();
System.out.println("Enter the values now: ");
for (int i = 1 ; i <= n_Elements ; i++) {
array[i] = in.nextInt();
}
for (int i = 1 ; i <= n_Elements ; i++) {
int num = 1;
if (array[i] == 0) {
System.out.println("\n1");
} else {
for (int j = 1 ; j <= array[i] ; j++) {
if (j % 2 != 0) {
num = num * 2;
} else {
num = num + 1;
}
}
System.out.println(num);
}
}
}
Output
Enter the number of Questions:
2
Enter the values now:
3
4
6
7
My approach is to take on account that first cycle (2 * height) occurs on odds indexes, and second cicle (1 + height) occurs on even indexes, from 1 to n (inclusive), starting index 0 is always 1.
return IntStream.rangeClosed(1, n)
.reduce(1, (acc, idx) -> idx % 2 != 0 ? acc * 2 : acc + 1);
This is my first contribution, only learning to code and solve algorithms, I had to find a workable solution with simple to follow code credit to http://www.javainterview.net/HackerRank/utopian-tree
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
//receive input
Scanner in = new Scanner(System.in);
//no of test cases
int T=in.nextInt();
//no of cycles
int[] N = new int[T];
for(int i=0;i<T;i++){
N[i]=in.nextInt();
}
int height=1;
for(int i=0;i<N.length;i++){
height=1;
for(int j=1;j<=N[i];j++){
if((j%2) ==1)
height=height*2;
else
height++;
}
System.out.println(height);
}
}
}//this the end of the class

Categories