What would be the next step in order to ask the user which of the numbers in this series of 30 he wants to see and prompts for an integer input - a number between 1 and 30 (inclusive)?
So if the user wants to see the fifth (5th) number of the Fibonacci series the user would input the integer 5 in response to the prompt.
public class MyFibonacci {
public static void main(String a[]) {
int febCount = 30;
int[] feb = new int[febCount];
feb[0] = 0;
feb[1] = 1;
for(int i=2; i < febCount; i++) {
feb[i] = feb[i-1] + feb[i-2];
}
for(int i=0; i< febCount; i++) {
System.out.print(feb[i] + " ");
}
}
}
Use a Scanner, or some InputStreamReader to read the input from the console. Scanner would be used in this way:
Scanner scanner = new Scanner(System.in);
if(scanner.hasNextInt())
int someInt = scanner.nextInt();
Another option would be to use some reader like this:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
and parse the required data from the output of the reader. Using Scanner will be simpler in most cases though.
public class Fibonacci_series // upto less than a given number
{
public static void main(long n)
{
long a=0, b=1, c=0;
while (c<n)
{
a=b;
b=c;
System.out.print(c+", ");
c=a+b;
}
System.out.print("....");
}
}
Here you go :
public class TestProgram {
public static void main(String a[]) {
Scanner reader = new Scanner(System.in);
printFibonacciSeries();
System.out.println("");
System.out.println("Fibonacci Series, Enter the number in the series of 30 you want to see");
int num = reader.nextInt();
int febCount = 30;
int[] feb = new int[febCount];
feb[0] = 0;
feb[1] = 1;
for (int i = 2; i < febCount; i++) {
feb[i] = feb[i - 1] + feb[i - 2];
if (i == num) {
System.out.print(feb[i] + " ");
}
}
}
public static void printFibonacciSeries() {
int febCount = 31;
int[] feb = new int[febCount];
feb[0] = 0;
feb[1] = 1;
for (int i = 2; i < febCount; i++) {
feb[i] = feb[i - 1] + feb[i - 2];
System.out.print(feb[i] + " ");
}
}
}
You could use a command line argument and read it from the main method args:
public class MyFibonacci {
public static void main(String a[]) throws NumberFormatException {
int febCount = Integer.parseInt(a[0]);
then call it with
java MyFibonacci 30
Or pass it in the 'VM options' input in an IntelliJ run configuration
Related
I tried to check the palindrome number and find the single digit sum of the palindrome numbers, but my code is not returning the proper value (I am finding it difficult to return the value of sum from the loops). Can anyone help me getting the mistake. Any help will be appriciated.
import java.util.Scanner;
public class SumOfPalindrome {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of array elements");
int n = sc.nextInt();
int[] inp = new int[n];
System.out.println("enter the elements");
for(int i = 0; i< n ;i++)
{
inp[i] = sc.nextInt();
}
System.out.println(SumOfPalindromeNumber(inp));
}
private static int SumOfPalindromeNumber(int[] inp )
{
int sumpal =0;
for(int i = 0; i<inp.length;i++)
{
int rem =0;
int sum = 0;
while(inp[i]!=0)
{
rem = inp[i]%10;
sum=(sum*10)+rem;
inp[i]/=10;
}
if(inp[i]==sum)
{
sumpal+=inp[i];
if(sumpal>9)
{
sumpal=singledigitsum(sumpal);
}
}
}
return sumpal;
}
private static int singledigitsum(int sumpal)
{
int rem1 = 0;
int sum1 = 0;
while(sumpal!=0)
{
rem1=sumpal%10;
sum1+=rem1;
sumpal/=10;
}
if(sum1>9)
{
sum1=singledigitsum(sum1);
}
return sum1;
}
}
Enter numbers
Check which numbers are palindromes.
If that number is a palindrome then find sum of its digits.
Code:
import java.util.Scanner;
public class SumOfPalindrome {
public static void main(String[] args) {
SumOfPalindrome sumOfPalindrome=new SumOfPalindrome();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of array elements");
int n = sc.nextInt();
int[] inp = new int[n];
System.out.println("enter the elements");
for(int i = 0; i< n ;i++)
{
inp[i] = sc.nextInt();
}
for(int i=0;i<n;i++)
{
if(sumOfPalindrome.isPallindrone(inp[i]))
{
System.out.println("No -> "+inp[i]+" Sum->"+sumOfPalindrome.sumOfDigits(inp[i]));
}
}
}//
public boolean isPallindrone(int no)
{
int r,sum=0,temp;
temp=no;
while(no>0){
r=no%10; //getting remainder
sum=(sum*10)+r;
no=no/10;
}
if(temp==sum)
{
return true;
}
else
{
return false;
}
}
public int sumOfDigits(int no)
{
int sum = 0;
while (no != 0)
{
sum = sum + no % 10;
no = no/10;
}
return sum;
}
}
I did not understand the purpose of sumpal in your code. You wanted a method which return sumOfPalindromes in an array. I commented the part which was wrong.
import java.util.Scanner;
public class SumOfPalindrome_1
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of array elements");
int n = sc.nextInt();
int[] inp = new int[n];
System.out.println("enter the elements");
for(int i = 0; i< n ;i++)
{
inp[i] = sc.nextInt();
}
//System.out.println(SumOfPalindromeNumber(inp));
SumOfPalindromeNumber(inp);
}
private static void SumOfPalindromeNumber(int[] inp )
{
int sumpal =0;
for(int i = 0; i<inp.length;i++)
{
int rem =0;
int sum = 0;
while(inp[i]!=0)
{
rem = inp[i]%10;
sum=(sum*10)+rem;
inp[i]/=10;
}
if(inp[i]==sum)
{
// sumpal+=inp[i];
/*if(sumpal>9)
{
sumpal=singledigitsum(sumpal);
}
*/
System.out.println(singleDigitSum(inp[i]));
}
}
}
private static int singleDigitSum(int sumpal)
{
int rem1 = 0;
int sum1 = 0;
while(sumpal!=0)
{
rem1=sumpal%10;
sum1+=rem1;
sumpal/=10;
}
if(sum1>9)
{
sum1=singleDigitSum(sum1);
}
return sum1;
}
}
Apologies if this is not the case but this seems like you are looking for answers to a coding test.
I'm trying to create a program that asks for 10 integers and puts those numbers into an array of negative, positive, and odd arrays. In the end, I want the program to print out 3 rows of numbers that separate the users 10 numbers into "odd", "even", and negative". When I run this I get "error: 'void' type not allowed here"
import java.util.Scanner;
public class ArrayPractice{
private static void showArray(int[] nums)
{
for (int i=0; i<nums.length;i++)
{
if(nums[i]!=0)
{
System.out.println(nums[i] + " ");
}
}
}
public static void main(String[] args){
int evenArray[] = new int[10];
int evenCount = 0;
int oddArray[] = new int[10];
int oddCount = 0;
int negArray[] = new int[10];
int negCount = 0;
Scanner input = new Scanner(System.in);
for(int i = 0; i<10; i++)
{
System.out.println("Number? " + (i + 1));
int answer = input.nextInt();
if(answer<0)
{
negArray[negCount++] = answer;
}
else
{
if (answer % 2 == 0)
{
evenArray[evenCount++] = answer;
}
else
{
oddArray[oddCount++] = answer;
}
}
}
System.out.println(showArray(evenArray));
System.out.println(showArray(oddArray));
System.out.println(showArray(negArray));
}
}
showArray is void, it does not return anything. And, on inspection, it prints in the method itself. So this
System.out.println(showArray(evenArray));
System.out.println(showArray(oddArray));
System.out.println(showArray(negArray));
should just be
showArray(evenArray);
showArray(oddArray);
showArray(negArray);
How can I fix this problem? I want to change parameter and pvalue as array
import java.util.*;
public class Test5 {
/**
* #param args the command line arguments
*/
int parameter[];
int pvalue[];
public Test5(int para[], int pv[]){
parameter=para;
pvalue=pv;
}
public void loopi(){
int i = 0,j,k,l;
Scanner sc=new Scanner(System.in);
System.out.print("enter parameter : ");
parameter[i]= sc.nextInt();
char group = 'a';
for(i=1;i<=parameter[i];i++)
{
System.out.print("enter parameter value : ");
pvalue[i]=sc.nextInt();
for(j=1;j<=pvalue[i];j++)
{
System.out.print(" "+j+group+" \n");
}
seat++;
}
}
public static void main(String[] args) {
// TODO code application logic here
int i[] = null;
int j[] = null;
Test5 t=new Test5(i,j);
t.loopi();
}
}
If you want to get the arrays as command line arguments, then you need to convert all of the strings in args to int, you could try something like
int[] a = new int[args.length];
for (int i = 0; i < args.length; i++) {
a[i] = Integer.parseInt(args[i]);
}
I am new to Java and I needed dynamic Array ... all of thing I found that's for dynamic Array we should use "Array List' that's ok but when I want the indexes to be the power of X that given from input , I face ERORR ! .. the indexes are unclear and the are not specified what is the first or 2th power ! .... can anyone help me how solve it?
public static void main(String[] args) throws Exception {
Scanner Reader = new Scanner(System.in);
ArrayList<Float> Zarayeb = new ArrayList<Float>();
Float s ;
int m;
System.out.print("Add Count of equation Sentences : ");
int N = Reader.nextInt();
if (N == 0)
return;
for (int i = 0; i < N ; i++) {
s = Reader.nextFloat() ;
System.out.print("x^");
m = Reader.nextInt();
if (Zarayeb.get(m)== null)
Zarayeb.add(0 , s);
else{
Float l ;
l = Zarayeb.get(m);
Zarayeb.add (m , l+s);
}
if (i < N-1)
System.out.print("\r+");
}
System.out.print("Add Count of equation Sentences : ");
N = Reader.nextInt();
if (N == 0)
return;
for (int i = 0; i < N ; i++) {
s = Reader.nextFloat() ;
System.out.print("x^");
m = Reader.nextInt();
if (Zarayeb.get(m)== null)
Zarayeb.add(m , s);
else{
Float l ;
l = Zarayeb.get(m);
Zarayeb.add (m , l+s);
}
if (i < N-1)
System.out.print("\r+");
}
System.out.print("Enter X: ");
float X = Reader.nextFloat();
float Sum = 0;
for (int i = 0; i < Zarayeb.size();i++) {
Sum += (Zarayeb.get(i) * Math.pow(X,i));
}
System.out.println("\nThe final answer is : " + Sum);
First I refactored your code a bit to make sense of it:
Main class with the top level logic:
import java.util.Scanner;
public class Main {
private Scanner scanner;
private final Totals totals = new Totals();
public static void main(final String[] args) {
final Main app = new Main();
app.run();
}
private void run() {
scanner = new Scanner(System.in);
try {
readAndProcessEquationSentences();
} finally {
scanner.close();
}
}
private void readAndProcessEquationSentences() {
readSentences(true);
readSentences(false);
System.out.println("The final answer is : " + totals.calculateSum(readBaseInput()));
}
private void readSentences(final boolean useInitialLogic) {
System.out.print("Enter number of equation sentences:");
final int numberOfSentences = scanner.nextInt();
if (numberOfSentences == 0) {
throw new RuntimeException("No sentences");
}
for (int i = 0; i < numberOfSentences; i++) {
Sentence sentence = Sentence.read(scanner);
if (useInitialLogic) {
totals.addInitialSentence(sentence);
} else {
totals.addNextSentence(sentence);
}
if (i < numberOfSentences - 1) {
System.out.print("\r+");
}
}
}
private float readBaseInput() {
System.out.print("Enter base: ");
return scanner.nextFloat();
}
}
Sentence class which represents one equation sentence entered by the user:
import java.util.Scanner;
public class Sentence {
private Float x;
private int y;
public static Sentence read(final Scanner scanner) {
final Sentence sentence = new Sentence();
System.out.println("Enter x^y");
System.out.print("x=");
sentence.x = scanner.nextFloat();
System.out.println();
System.out.print("y=");
sentence.y = scanner.nextInt();
System.out.println();
return sentence;
}
public Float getX() {
return x;
}
public int getY() {
return y;
}
}
Totals class which keeps track of the totals:
import java.util.ArrayList;
import java.util.List;
public class Totals {
private final List<Float> values = new ArrayList<Float>();
public void addInitialSentence(final Sentence sentence) {
if (values.size() <= sentence.getY()) {
addToStart(sentence);
} else {
addToValue(sentence);
}
}
private void addToStart(final Sentence sentence) {
values.add(0, sentence.getX());
}
public void addNextSentence(final Sentence sentence) {
if (values.size() <= sentence.getY()) {
values.add(sentence.getY(), sentence.getX());
} else {
addToValue(sentence);
}
}
private void addToValue(final Sentence sentence) {
Float total = values.get(sentence.getY());
total = total + sentence.getX();
values.add(sentence.getY(), total);
}
public float calculateSum(final float base) {
float sum = 0;
for (int i = 0; i < values.size(); i++) {
sum += (values.get(i) * Math.pow(base, i));
}
return sum;
}
}
I don't have the foggiest idea what this is supposed to do. I named the variables according to this foggy idea.
You are letting the user input values in two separate loops, with a slightly different logic I called 'initial' and 'next'.
In the initial loop you were doing this:
if (Zarayeb.get(m) == null)
Zarayeb.add(0 , s);
In the next loop this:
if (Zarayeb.get(m) == null)
Zarayeb.add(m , s);
There are problems with this because the ArrayList.get(m) will throw an IndexOutOfBoundException if m is out or range. So I changed that to the equivalent of:
if (Zarayeb.size() <= m) {
....
}
However, in the 'next' case this still does not solve it. What should happen in the second loop when an 'm' value is entered for which no element yet exists in the ArrayList?
Why do you need to enter sentences in two loops?
What is the logic supposed to achieve exactly?
Can you give me a hint on what I'm doing wrong with my average in the average method? I'm trying to call the method in the read scores.I'm trying to get the average of the scores I have in my input.txt file.
import java.io.*;
import java.util.*;
public class FindGrade {
public static final int NUM_SCORE_TYPES = 5;
public static void main(String[] args) {
Scanner scan = null;
int[] quizArray = null;
int[] labArray = null;
int[] attendance = null;
int[] midterms = null;
int quizgrade =0;
int labgrade=0;
int attendance_1=0;
int midterms_1 =0;
String name;
try {
scan = new Scanner(new File("input.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
// each iteration is for single exam type (ie: Quizzes is the 1st one)
for (int i = 0; i < NUM_SCORE_TYPES; i++) {
name = scan.next();
int numScores = scan.nextInt();
int maxGrade = scan.nextInt();
if (name.equals("Quizzes")) {
quizArray = new int[numScores];
readScores(quizArray, numScores, scan);
}
else if (name.equals("Labs")) {
labArray = new int[numScores];
readScores(labArray, numScores, scan);
}
else if (name.equals("Lab_attendance")) {
attendance = new int[numScores];
readScores(attendance, numScores, scan);
}
else if (name.equals("Midterms")) {
midterms = new int[numScores];
readScores(midterms, numScores, scan);
}
}
}
public static void readScores(int[] scoreArray, int numScores, Scanner scan) {
for (int i = 0; i < numScores; i++) {
scoreArray[i] = scan.nextInt();
}
}
public static void average(double [] scoreArray, int numScores){
double sum=0;
for(int i=0; i< scoreArray.length; i++){
sum += scoreArray[i];
}
double average = sum/numScores;
System.out.println(sum + " " + average);
}
In any case, you can't directly call it with the arrays that you are creating there. Because the arrays are of type int, but the average-method requires a double array. When you change this, you can call the method like this...
public static void readScores(int[] scoreArray, int numScores, Scanner scan) {
for (int i = 0; i < numScores; i++) {
scoreArray[i] = scan.nextInt();
}
average(scoreArray, numScores); // <----- Call it here
}
public static void average(int[] scoreArray, int numScores){
double sum=0;
for(int i=0; i< scoreArray.length; i++){
sum += scoreArray[i];
}
double average = sum/numScores;
System.out.println(sum + " " + average);
}