I need help with my java-program. This program is supposed to ask for the highest value fibonacci can have, and print out the number of series up to that value, but it doesn't work. Any suggestions?
import java.util.Scanner;
public class Fibonacci {
public static void main (String[] args){
Scanner in = new Scanner(System.in);
System.out.println("The largest number fibonacci can be: ");
int number = in.nextInt();
if (number < 0){
System.out.println("Wrong! Max-value has to be at least 0.");
}
int i;
int f0 = 0;
int f1 = 1;
int fn;
int value=0;
for (i = 0; i<=value; i++){
fn = f0 + f1;
System.out.println("Fibonacci-number " + i + " = " + f0);
f0 = f1;
f1 = fn;
value = number - f0;
}
}
}
If i put in number = 12, the program is supposed to print:
fibonacci-number 0 = 0
...
fibonnaci-number 12 = 144
Just change the loop to compare value of increment-er (i) to 'number ' variable
for (i = 0; i<=number; i++){
//.........
}
Also use double instead of int if you want to print higher number in the series correctly.
There is no use of the 'value' variable.
Also, the phrase 'the highest value fibonacci can have' is misleading.You have mentioned number denotes number of terms in the series in your example.
If you want 'number' to be the highest value in the series, use following approach,
do{
fn = f0 + f1;
System.out.println("Fibonnaci-tall " + i + " = " + f0);
f0 = f1;
f1 = fn;
i++;
}while(f0<=number);
Is this what you are looking for?
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int f0 = 0;
int f1 = 1;
int fn = 0;
System.out.println("The largest number fibonnaci can be: ");
System.out.println("Input your number: ");
int number = in.nextInt();
if (number < 0){
System.out.println("Wrong! Max-value has to be at least 0.");
} else {
System.out.println(f0);
System.out.println(f1);
while (fn < number){
fn = f0 + f1;
f0 = f1;
f1 = fn;
if (fn < number){
System.out.println(fn);
}
}
}
}
enter image description here
Use this program, it will solve your query.
Try this...It works!
public static void main (String[] args){
Scanner in = new Scanner(System.in);
System.out.println("The largest number fibonacci can be: ");
int number = in.nextInt();
if (number < 0){
System.out.println("Wrong! Max-value has to be at least 0.");
}
else{
int i=0;
int f0 = 0;
int f1 = 1;
int fn;
int value=0;
do{
//for (i = 0; i<=value; i++){
fn = f0 + f1;
System.out.println("Fibonacci-number " + i + " = " + f0);
f0 = f1;
f1 = fn;
value = number - f0;
i++;
}while(f0<=number);
}//else
}
Related
I am writing a program that reverses 2 4 digit numbers, and I wrote a method that will do it. There are no errors in the project build, but I get "String index out of range: -3" when I try to run it. I am fairly new to programming and I have no idea what I did wrong.
Here's the code:
public static void main(String[] args)
{
int num1 = 1;
int num2 = 1;
Scanner console = new Scanner(System.in);
while (num1 <1000 || num1 > 9999)
{
System.out.println("Please enter a positive 4 digit number");
num1 = console.nextInt();
}
String numString1 = Integer.toString(num1);
while (num2 <1000 || num2 > 9999)
{
System.out.println("Please enter another positive 4 digit number");
num2 = console.nextInt();
}
String numString2 = Integer.toString(num2);
int numReverse1 = stringReverse(numString1);
int numReverse2 = stringReverse(numString2);
System.out.println(numReverse1 + numReverse2);
System.out.println("The product of your 2 reversed numbers is: " + (numReverse1 * numReverse2));
}
public static int stringReverse (String numString)
{
String c1c2c3 = numString.substring(4);
String c2c3c4 = numString.substring(1);
String c1c2 = c1c2c3.substring(3);
String c3c4 = c2c3c4.substring(1);
String c1 = c1c2.substring(2);
String c2 = c1c2.substring(1);
String c3 = c3c4.substring(2);
String c4 = c3c4.substring(1);
String numStringReverse = c4 + c3 + c2 + c1;
int reversedString = Integer.parseInt(numStringReverse);
return reversedString;
}
}
In the line:
String c1c2c3 = numString.substring(4);
String c1c2 = c1c2c3.substring(3);
You are trying to access a position that does not exists. Arrays in Java are started by 0 til " - 1".
Start index is inclusive, end index is exclusive in substring method.
A correct version for stringReverse` would be this:
public static int stringReverse (String numString)
{
String c1c2c3 = numString.substring(0,3);
String c2c3c4 = numString.substring(1,4);
String c1c2 = c1c2c3.substring(0,2);
String c3c4 = c2c3c4.substring(1,3);
String c1 = c1c2.substring(0,1);
String c2 = c1c2.substring(1,2);
String c3 = c3c4.substring(0,1);
String c4 = c3c4.substring(1,2);
String numStringReverse = c4 + c3 + c2 + c1;
int reversedString = Integer.parseInt(numStringReverse);
return reversedString;
}
Also, try reading this answer.
There are perhaps more elegant ways to reverse a string in Java. If you want an easy alternative in Java look at the class java.lang.StringBuilder.
Check the documentation and look for the reverse method.
I know how to code to find the factorial of a number:
public static void factorialcalculations()
{
int usernumber, calculation, fact = 1;
System.out.println("Enter an integer to calculate it's factorial");
Scanner in = new Scanner(System.in);
usernumber = in.nextInt();
if ( usernumber < 0 )
System.out.println("Number should be non-negative.");
else
{
for ( calculation = 1 ; calculation <= usernumber ; calculation++ )
fact = fact*calculation;
System.out.println("Factorial of "+usernumber+" is = "+fact);
{
But what I need is for is to display what numbers it is being multiplied by for example if it was 5
I need it to display the factorial is: 5*4*3*2*1=120
Use recursion. The value you want to display for n=1 is "1=". For any other n, it's "n*" + display(n-1).
display(2) => "2*" + display(1) => "2*1="
display(3) => "3*" + display(2) => "3*2*1="
and so on.
There is lot of ways to do it. With your existing code you can print it within your existing loop. Recursive will be the elegant way to find the factorial.
public static int factorial(int n) {
System.out.print("factorial is : ");
int result = 1;
for (int i = n; i >= 1; i--) {
result = result * i;
System.out.print(i!=1 ? (i+"*"): (i+"="));
}
System.out.println(result);
return result;
}
PS: As a best practice you need to handle the all scenarios in here. (String/negative/.. inputs)
Here is what you seem to be looking for man:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number whose factorial is to be found: ");
int n = scanner.nextInt();
int result = factorial(n);
System.out.println(getFactString(n,result));
}
public static int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result = result * i;
}
return result;
}
public static String getFactString(int n, int result){
String output= "";
int count = n;
for (int i = count; i > 0; i--) {
if (n==1) {
output = output + n +" = ";
break;
}
output = output + n+" * ";
n--;
}
return output + result;
}
It's also possible to do this will StringBuilder as well. With the getFactorString() method, it doesn't matter what n is, you will get the correct string returned to display.
How can I input a String and an int in the same line? Then I want to proceed it to get the largest number from int that I already input:
Here is the code I have written so far.
import java.util.Scanner;
public class NamaNilaiMaksimum {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String name[] = new String[6];
int number[] = new int[6];
int max = 0, largest = 0;
int as = 5;
for (int x = 1; x <= as; x++) {
System.out.print(" Name & number : ");
name[x] = in.nextLine();
number[x] = in.nextInt();
}
for (int x = 1; x <= as; x++) {
if (number[x] > largest) {
largest = number[x];
}
}
System.out.println("Result = " + largest);
}
}
There's an error when I input the others name and number.
I expect the output will be like this
Name & Number : John 45
Name & Number : Paul 30
Name & Number : Andy 25
Result: John 45
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String InputValue;
String name[] = new String[6];
int number[] = new int[6];
String LargeName = "";
int largest = 0;
int as = 5;
for (int x = 1; x <= as; x++) {
System.out.print(" Name & number : ");
InputValue = in.nextLine();
String[] Value = InputValue.split(" ");
name[x] = Value[0];
number[x] = Integer.parseInt(Value[1]);
}
for (int x = 1; x < number.length; x++) {
if (number[x] > largest) {
largest = number[x];
LargeName = name[x];
}
}
System.out.println("Result = " + LargeName + " " + largest);
}
Hope this works for you.
System.out.print(" Name & number : ");
/*
Get the input value "name and age" separated with space " " and splite it.
1st part is name and second part is the age as tring format!
*/
String[] Value = in.nextLine().split(" ");
name[x] = Value[0];
// Convert age with string format to int.
number[x] = Integer.parseInt(Value[1]);
Having trouble with this final program for my Java class. We have to only use concepts we have learned so far so I cannot use other classes. Basically just loops and arrays and methods.
So for this program we have to add any five sets of fractions entered and give the GCD and the results in the lowest form. I have to show all data in the first table and then a second table with the original data and the GCD and the results in the lowest form. It has to be tested with this data:
1/4 + 1/2
2/3 + 1/3
7/8 + 1/8
2/9 + 4/27
7/25 + 2/5
Here is the code I have so far. (Be gentle, I'm still new at this)
import java.util.Scanner;
public class HelloWorld{
public static void main(String[] args) throws Exception{
int[] num1Array = new int[5];
int[] num2Array = new int[5];
int[] deno1Array = new int[5];
int[] deno2Array = new int[5];
Scanner input = new Scanner(System.in);
for(int x=0;x<5;x++) { //Get all data from user
System.out.println("Enter data for problem " + (x+1));
System.out.println("Enter numberator for fraction 1");
num1Array[x] = input.nextInt();
System.out.println("Enter denominator for fraction 1");
deno1Array[x] = input.nextInt();
System.out.println("Enter numberator for fraction 2");
num2Array[x] = input.nextInt();
System.out.println("Enter denominator for fraction 2");
deno2Array[x] = input.nextInt();
System.out.println("********************");
}
System.out.println("*****ORIGINIAL DATA ******"); //Output all entered data
System.out.println("First Fraction \t Second Fraction");
for(int y=0;y<5;y++) {
System.out.printf("%1d/%1d \t\t %1d/%1d\n", num1Array[y], deno1Array[y], num2Array[y], deno2Array[y]);
}
System.out.println("*******FRACTIONS SHOWING ADDED RESULTS*********"); //Display results
System.out.println("First Fraction \t Second Fraction GCD Results");
for(int z=0;z<5;z++){
int finalgcd = gcdfinal(num1Array[z], num2Array[z], deno1Array[z], deno2Array[z]);
int addFrac = fracAdd(num1Array[z], num2Array[z], deno1Array[z], deno2Array[z]);
System.out.printf("%1d/%1d \t\t %1d/%1d\t\t %1d \t %1d", num1Array[z], deno1Array[z], num2Array[z], deno2Array[z], finalgcd, addFrac);
System.out.println();
}
}
public static int fracAdd(int num1, int num2, int deno1, int deno2)
{
int e = lcm(deno1, deno2); //denominator
int f1 = e / deno1;
int f2 = e / deno2;
int g1 = num1 * f1;
int g2 = num2 * f2;
int adding = g1 + g2;
int k = gcd(adding, e);
int final_num = adding / k;
int final_deno = e / k;
if(final_num == final_deno){
return 1;
}
else {
return (final_num, final_deno);
}
}
public static int gcd(int a, int b) //Calculate GCD
{
while (b > 0)
{
int temp = b;
b = a % b;
a = temp;
}
return a;
}
public static int gcdfinal(int num1, int num2, int deno1, int deno2)
{
int e = lcm(deno1, deno2); //Calculate the GCD for display
int f1 = e / deno1;
int f2 = e / deno2;
int g1 = num1 * f1;
int g2 = num2 * f2;
int end = g1 + g2;
int k = gcd(end, e);
return k;
}
public static int lcm(int a, int b) //Calculate LCM
{
return a * (b / gcd(a, b));
}
}
How can I approach doing this? Am I on the right track?
Try with this, hopefully it helps you. :)
import java.util.Scanner;
public class AddingFraction {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("please enter a fraction number in a/b format: ");
String fraction1 = sc.nextLine();
System.out.println("please enter another fraction number in a/b format: ");
String fraction2 = sc.nextLine();
addFractions(fraction1, fraction2);
}
public static void addFractions(String fractionNum1, String fractionNum2) {
int numResult = 0;
String resultFraction;
String[] frcNum1 = fractionNum1.split("/");
int numerator1 = Integer.parseInt(frcNum1[0]);
int Denomenator1 = Integer.parseInt(frcNum1[1]);
String[] frcNum2 = fractionNum2.split("/");
int numerator2 = Integer.parseInt(frcNum2[0]);
int Denomenator2 = Integer.parseInt(frcNum2[1]);
if (Denomenator1 == Denomenator2) {
numResult = numerator1 + numerator2;
resultFraction = numResult + "/" + Denomenator1;
System.out.println("Resultant Fraction is : "+resultFraction);
} else {
int denLcm = Denomenator1 * (Denomenator2 / gcd(Denomenator1, Denomenator2));;
numResult = numerator1 * (denLcm / Denomenator1) + numerator2
* (denLcm / Denomenator2);
resultFraction = numResult + "/" + denLcm;
System.out.println("Resultant Fraction is : "+resultFraction);
}
}
private static int gcd(int a, int b) {
while (b > 0) {
int temp = b;
b = a % b; // % is remainder
a = temp;
}
return a;
}
}
I am trying to get the averages of values in a text file. The content of the file is:
Agnes 56 82 95 100 68 52
Bufford 87 92 97 100 96 85 93 77 98 86
Julie 99 100 100 89 96 100 92 99 68
Alice 40 36 85 16 0 22 72
Bobby 100 98 92 86 88
I have to skip the names, and try to sum the values of the integers of each line. The ouput should be something like this:
Agnes, average = 76
Bufford, average = 91
Julie, average = 94
Alice, average = 39
Bobby, average = 93
My problem is that i am unable to sum the values (using sum+=sc1.nextInt()). I also cant count the number of tokens of just the integers. For example, for the first line I need countTokens to equal 6, but i get 7, even after I skip the name.
import java.io.*;
import java.util.*;
public class studentAverages
{
public static void main() throws IOException
{
Scanner sf = new Scanner(new File("C:\\temp_Name\\StudentScores.in"));
int maxIndex = -1;
String text[] = new String[100];
while(sf.hasNext( ))
{
maxIndex++;
text[maxIndex] = sf.nextLine();
}
sf.close();
int sum=0;
int avg=0;
int divisor=0;
for (int i=0;i<=maxIndex; i++)
{
StringTokenizer sc= new StringTokenizer(text[i]);
Scanner sc1= new Scanner (text[i]);
while (sc1.hasNext())
{
sc1.useDelimiter(" ");
sc1.skip("\\D*");
System.out.print(sc1.nextInt());
System.out.println(sc1.nextLine());
sum+=sc1.nextInt(); // trying to sum all the numbers in each line, tried putting this line everywhere
avg=sum/divisor;
break;
}
System.out.println(avg);
while (sc.hasMoreTokens())
{
divisor=sc.countTokens()-1; //Not able to count tokens of just the numbers, thats why I am using -1
//System.out.println(divisor);
break;
}
}
//this is for the output
/*for (int i=0; i<=maxIndex; i++)
{
String theNames="";
Scanner sc= new Scanner (text[i]);
theNames=sc.findInLine("\\w*");
System.out.println(theNames + ", average = ");
}*/
}
}
I would recommend splitting each line using the split method and then looping through those values while ignoring the first, because you know that is the title.
public static void main() throws IOException {
Scanner sf = new Scanner(new File("C:\\temp_Name\\StudentScores.in"));
int maxIndex = -1;
String text[] = new String[100];
while(sf.hasNext( )) {
maxIndex++;
text[maxIndex] = sf.nextLine();
}
sf.close();
for(int i = 0; i < maxIndex; i ++) {
String[] values = text[i].split(" ");
String title = values[0];
int sum = 0;
for(int j = 1; i < values.length; j ++) {
sum += Integer.parseInt(values[j]);
}
double average = sum / (values.length - 1);
System.out.println(title + ": " + average);
}
}
Notice that the inner loop's index begins at 1 and not 0, and that when calculating the average, we subtract one from the size of the values array because we want to ignore the title.
Try this one:
Scanner scanner = new Scanner(new File("resources/abc.txt"));
//check for next line
while (scanner.hasNextLine()) {
//create new scanner for each line to read string and integers
Scanner scanner1 = new Scanner(scanner.nextLine());
//read name
String name = scanner1.next();
double total = 0;
int count = 0;
//read all the integers
while (scanner1.hasNextInt()) {
total += scanner1.nextInt();
count++;
}
System.out.println(name + ", average = " + (total / count));
}
scanner.close();
output:
Agnes, average = 75.5
Bufford, average = 91.1
Julie, average = 93.66666666666667
Alice, average = 38.714285714285715
Bobby, average = 92.8
--EDIT--
Here is the code as per your last comment (I have to use StringTokenizer`/string methods like useDelimiter, skip, etc to arrive at the answer)
Scanner sf = new Scanner(new File("resources/abc.txt"));
List<String> text = new ArrayList<String>();
while (sf.hasNext()) {
text.add(sf.nextLine());
}
sf.close();
for (String str : text) {
StringTokenizer sc = new StringTokenizer(str, " ");
double sum = 0;
int count = 0;
String name = sc.nextToken();
while (sc.hasMoreElements()) {
sum += Integer.valueOf(sc.nextToken());
count++;
}
System.out.println(name + ", average = " + (sum / count));
}
}
output
Agnes, average = 75.5
Bufford, average = 91.1
Julie, average = 93.66666666666667
Alice, average = 38.714285714285715
Bobby, average = 92.8