Taking multiline inputs in java command line - java

The problem I'm trying to solve is given an integer N find the digits in this number that exactly divide N(division that leaves 0 as remainder) and display their count. For N=24, there are 2 digits − 2 & 4. Both of these digits exactly divide 24. So our answer is 2. The input format is The first line contains T (number of test cases) followed by T lines (each containing an integer N).
Here's my code
public static void main(String[] args) throws IOException {
System.out.println("Please enter your inputs");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
ArrayList<String> arr = new ArrayList<String>();
int i=0;
while ((line = br.readLine()) != null && line.length() != 0){
arr.add(line);
i++;
}
if(Integer.parseInt(args[0]) != (args.length -1)){
System.out.println("Wrong number of inputs");
}else{
for(int j = 1; j< args.length; j++){
System.out.println(findDivisor(Integer.parseInt(args[j])));
}
}
}
public static int findDivisor(int n){
int count = 0;
String s = Integer.toString(n);
char[] c= s.toCharArray();
for(int i = 0; i< c.length; i++){
String temp = Character.toString(c[i]);
int num = Integer.parseInt(s);
if(num == 0)
count += 0;
else if(n%num == 0){
count +=1;
}
}
return count;
}
On adding an Arraylist to read to inputs, the program goes into an infinite loop it seems. As in based on the first input I need to take the number of inputs and then process. As in if the first input is 2, my program should await 2 more command line inputs and on the third press of enter run. How do I invoke that functionality into this code.

Try using the Scanner class:
import java.util.Scanner;
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
// Read in T.
int T = sc.nextInt();
// Read in T integers, for each print the number of digit divisors.
for (int i = 0; i < T; i++){
int n = sc.nextInt()
System.out.println(findDivisor(n));
}
}
If you want to wait until all input is in first, create an array of size T to keep track of your integers:
import java.util.Scanner;
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
// Read in T.
int T = sc.nextInt();
int[] myNumbers = new int[T];
// Read in all input, and calculate the number of digit divisors.
for (int i = 0; i < T; i++){
int n = sc.nextInt()
myNumbers[i] = findDivisor(n);
}
// For each input, print out the number of digit divisors.
System.out.println("Number of digit divisors:");
for (int i = 0; i < T; i++){
System.out.println(myNumbers[i]);
}
}

Related

Showing a null value instead of token value

I am creating this code where I am supposed to prompt the user for a maximum of 5 integer numbers. I should store the 5 integers in an array by asking the user to enter them until the array is full or the user exits by entering -99. Then I should print out all the values of the array and calculate the average. The problem is that when I scan and store the values it shows me a null value of 0 of the fifth number instead of the number itself and it does not count it with the sum. This is the piece of code I've been working with:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean cond = false;
int i = 0;
int[] number = new int[5];
double sum = 0;
do{
int num = scan.nextInt();
if(num==-99 || i==4){
for(int k=0; k<i+1; k++){
System.out.println(number[k]);
sum = sum + number[k];
}
System.out.println(sum/i);
cond = true;
}
number[i] = num;
i++;
}while(!cond);
}
This is the input : 1 2 3 4 5
Every number is on a separate line
This is the output:
run:
1
2
3
4
5
1
2
3
4
0
2.5
number[i] = num;
is what adds the number the user entered to the array. If they enter -99, it's in the correct place. If they've simply entered all 4 however, it is in the wrong place. Also, you have it so it is actually dividing by the wrong number. Something like this should work:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean cond = false;
int i = 0;
int[] number = new int[5];
double sum = 0;
do{
int num = scan.nextInt();
if(num!=-99){
number[i] = num;
i++;
}
if(num==-99 || i==5){
for(int k=0; k<i; k++){
System.out.println(number[k]);
sum = sum + number[k];
}
System.out.println(sum/(i));
cond = true;
}
}while(!cond);
}
Also, do while loops are really ugly, and you can do it much smoother with just two for loops:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] number = new int[5];
double sum = 0;
int num=0,i;
for(i=0;i<5&&num!=-99;i++){
num = scan.nextInt();
number[i] = num;
}
for(int k=0;k<i;k++){
System.out.println(number[k]);
sum+=number[k];
}
System.out.println(sum/(i+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)));
}

The sum of all the multiples of 3 or 5 below N

I have to find the sum of all the multiples of 3 or 5 below N.
example if we have to list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9,the sum of these multiples is 23.
Now the only problem left is that I want it to be able to read ALL the numbers THEN display the sum, for now it reads one number and display the sum right after it, any ideas?
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Solution{
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
int Nbr = Integer.parseInt(line);
for(int j=0; j<Nbr;j++)
{
BufferedReader br2 = new BufferedReader(new InputStreamReader(System.in));
String line2 = br2.readLine();
String[] numbers = new String[Nbr];
numbers[j]= line2;
System.out.println(Somme(Long.parseLong(numbers[j])));
}
}
public static long Somme(long Nn) {
long s = 0;
for (int i = 0; i < Nn; i++) {
if (((i % 3) == 0) || ((i % 5) == 0)) {
s = s + i;
}
}
return (s);
}
}
I suggest you use a Scanner. I would also suggest you add to a sum by iterating from 3 to n in increments of 3. Then from 5 to n in increments of 5 (then exclude the multiples of 3, because they've already been added). Something like
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
int n = scanner.nextInt();
System.out.println(getSum(n));
}
}
public static long getSum(int n) {
long sum = 0;
for (int i = 3; i < n; i += 3) {
sum += i;
}
for (int i = 5; i < n; i += 5) {
if (i % 3 != 0) { // <-- already added if i is divisible by 3
sum += i;
}
}
return sum;
}
Based on your comment below, change main to first read the int of counts, then store them in an array. Something like
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
int toRead = scanner.nextInt();
int[] vals = new int[toRead];
for (int t = 0; t < toRead; t++) {
if (scanner.hasNextInt()) {
vals[t] = scanner.nextInt();
}
}
StringBuilder sb = new StringBuilder();
for (int n : vals) {
sb.append(getSum(n)).append(" ");
}
System.out.println(sb);
}
}
Move your print statement outside the loop.
Before loop,
long[] sumArr = new long[Nbr];
inside loop,
sumArr[j] = Somme(Long.parseLong(numbers[j]));
after loop,
for (long sum : sumArr) {
System.out.println(sum);
}
If u want to read all Ns first then ,read them and put them in an array then try to find the sum
You can make ArrayList and add the sum to it then print it after the loop
As we know that we need to sum of those numbers which are divisible by 3 or 5 below n where n=10 or 100 or more (it is limit). But if we have n=20 so 15(15%5==0 && 15%3==0) will come twice so that we need to add only once so that we need to check a number is divisible by 15(since 5*3=15).
long n1=0,n2=0;
int i=1,j=1;
while(3*i<n)
{
n1 +=3*i;
i++;
if(5*j<n)
{
n2+=5*j;
if(5*j%15==0)
n2 -=5*j;
j++;
}
}
System.out.println(n1+n2);
}
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) {
Scanner in = new Scanner(System.in);
int sum = 0;
int t = in.nextInt();
for(int a0 = 0; a0 < t; a0++){
long n = in.nextInt();
for(int j=1;j < n;j++)
if(j % 3 == 0 || j%5 == 0){
sum+=j;
}
System.out.println(sum);
sum = 0;
}
}
}
This is simple Solution

Stop and print array from user input

I am new at java programming and am working on an exercise where the user is to input ints into an array and then stop the user input by entering a negative int value. All works well except the array prints 0 beyond the user input. So if a user enters 5 values and then one negative value only the five values should print not the user input values and 95 0s.
Any assistance would be greatly appreciated.
Here is my code:
public static void main (String str[]) throws IOException {
Scanner scan = new Scanner (System.in);
int array[] = new int [100];
System.out.println ("Enter values up to 100 values, " +
"enter a negative number to quit");
for (int i=0; i< array.length; i++)
{
array[i] = scan.nextInt();
if (array [i] < 0)
{
break;
}
}
for (int i =0; i<array.length; i++)
{
System.out.println(array[i]);
}
}
When you declare an int in Java, it will default to 0 if you do not specify a value for it. When you declare your array,
int array[] = new int [100];
You are essentially making an array of 100 0's. You can see a small example of this by running the following code:
public static void main(String[] args) throws Exception {
int array[] = new int [1];
System.out.println("The value of i is: " + array[0]);
}
What you could do, is store the negative value into your array, and then stop printing if you reach that value.
for (int i =0; i<array.length; i++){
if(array[i]<0){
break;
}
System.out.println(array[i]);
}
public static void main (String str[]) throws IOException {
Scanner scan = new Scanner (System.in);
int array[] = new int [100];
int totalValuesEntered = 0;
System.out.println ("Enter values up to 100 values, " +
"enter a negative number to quit");
for (int i=0; i< array.length; i++)
{
array[i] = scan.nextInt();
if (array[i] < 0)
{
totalValuesEntered = i;
break;
}
}
System.out.println("Your entries are:");
for (int i =0; i<totalValuesEntered; i++)
{
System.out.println(array[i]);
}
}
You are looping 100 times no matter what on the last loop, and you are saving the userinput no matter what they enter.
In order to achieve what you want. Declare a new integer enteredValues to count how many values the user entered before exiting.
public static void main(String str[]) throws IOException {
Scanner scan = new Scanner(System. in );
int array[] = new int[100];
System.out.println("Enter values up to 100 values, " +
"enter a negative number to quit");
int enteredValues = 0;
for (int i = 0; i < array.length; i++) {
int userInput = scan.nextInt(); //save nextInt to a variable
if (userInput >= 0) {
array[i] = userInput;
enteredValues++;
} else{
break;
}
}
for (int i = 0; i < enteredValues; i++) {
System.out.println(array[i]);
}
}

Taking User Input for an Array

A link to the assignment:
http://i.imgur.com/fc86hG9.png
I'm having a bit of trouble discerning how to take a series of numbers and apply them to an array without a loop. Not only that, but I'm having a bit of trouble comparing them. What I have written so far is:
import java.util.Scanner;
public class Lottery {
public static void main(String[] args) {
int userInputs[] = new int[5];
int lotteryNumbers [] = new int[5];
int matchedNumbers =0;
char repeatLottery = '\0';
Scanner in = new Scanner (System.in);
do{
System.out.println("Enter your 5 single-digit lottery numbers.\n (Use the spacebar to separate digits): ");
for(int i = 0; i <5; i++ )
userInputs[i] = in.nextInt();
System.out.println("Your inputs: ");
printArray(userInputs);
System.out.println("\nLottery Numbers: ");
readIn(lotteryNumbers);
for(int i=0; i<5; i++) {
System.out.print(lotteryNumbers[i] + " ");
}
matchedNumbers = compareArr(userInputs, lotteryNumbers);
System.out.println("\n\nYou matched " + matchedNumbers + " numbers");
System.out.println("\nDo you wish to play again?(Enter Y or N): ");
repeatLottery = in.next().charAt(0);
}
while (repeatLottery == 'Y' || repeatLottery == 'y');
}
public static void printArray(int arr[]){
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
public static void readIn(int[] List) {
for(int j=0; j<List.length; j++) {
List[j] = (int) (Math.random()*10);
}
}
public static int compareArr (int[] list1, int[] list2) {
int same = 0;
for (int i = 0; i <= list1.length-1; i++) {
for(int j = 0; j <= list2.length-1; j++) {
if (list1[i] == list2[j]) {
same++;
}
}
}
return same;
}
}
As you'll notice, I commented out the input line because I'm not quite sure how to handle it. If I have them in an array, I should be able to compare them fairly easily I think. This is our first assignment handling arrays, and I think it seems a bit in-depth for only having one class-period on it; So, please forgive my ignorance. :P
Edit:
I added a new method at the end to compare the digits, but the problem is it compares them in-general and not from position to position. That seems to be the major issue now.
your question isn't 100% clear but i will try my best.
1- i don't see any problems with reading input from user
int[] userInput = new int[5]; // maybe here you had a mistake
int[] lotterryArray = new int[5]; // and here you were declaring your arrays in a wrong way
Scanner scanner = new Scanner(system.in);
for ( int i = 0 ; i < 5 ; i++)
{
userInput[i] = scanner.nextInt();
} // this will populate your array try to print it to make sure
Edit : important in the link you shared about the assignment the compare need to check the value and location so if there are two 5 one in input one in loterry array they need to be in the same location check the assignment again
// to compare
int result = 0 ; // this will be the number of matched digits
for ( int i = 0 ; i < 5 ; i++)
{
if ( userInput[i] == loterryArray[i] )
result++
}
// in this comparsion if the digits are equale in value and location result will be incremented

Categories