trying to print arrays in java [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I had a code I needed to submit and every time I try to run it, I get the same errors over and over again.
Here's the question
Write the following Java methods:
(a). readValues to input ten integer values into an array of integers
TAB from a text file “Values.txt”. This array TAB is passed to the
method as parameter. Assume that the number of students in the file is
equal to the length of the array.
(b). oddValues that takes the array TAB as parameter and returns the
number of odd values found in TAB.
(c). replaceOdd that takes the array TAB as a parameter. It should
replace every odd value in TAB by the sum of all odd values.
Hint: your method must first compute the sum of all odd values.
(d). printValues that takes the array TAB as a parameter and prints
its content on the screen.
(e). main that declares the array TAB and calls the above four
methods.
N.B.: In your program, use the methods and variable names as mentioned
above.
And this is the code:
import java.util.*;
import java.io.*;
public class Finalexam
{
public static void main (String [] args ) throws FileNotFoundException
{
int sum=0;
int [] TAB=new int [10];
ReadValues(TAB);
oddValues(TAB);
replaceOdd(TAB);
printValues(TAB);
System.out.println("The sum is" + sum);
}
public static void ReadValues (int [] TAB)
{
{ int i;
for(i=0; i<10; i++){
Scanner s = new Scanner ("Values.txt") ;
TAB[i]=s.nextInt();
}
}
s.close();
}
public static double oddValues(int[] TAB)
{
int i;
double odd=0;
int fn=0;
for(i=1; i<odd; i++){
while(odd % 2 !=0)
{
odd = fn;
}
break;
}
return fn;
}
public static int replaceOdd(int[] TAB)
{
int re=0;
for(int i=0; i<TAB.length; i++){
re = re/TAB.length;
}
return re;
}
public static void printValues(int[] TAB)
{
int i;
for(i=0; i<10; i++){
System.out.println(TAB[i]+"\t");
}
System.out.println();
}
}
In which part I'm doing wrong? I cant even run it.

Firstly there is a compilation error in your code.
In your method
public static void ReadValues (int [] TAB)
{
{ int i;
for(i=0; i<10; i++){
Scanner s = new Scanner ("Values.txt") ;
TAB[i]=s.nextInt();
}
}
s.close();
}
You have too many extra brackets, well thats not the problem though, the problem is the scanner object s is declared inside the for loop where as you are closing it later outside the loop, since the scope of the variable is not outside the loop, hence the error.
The correct way should be
public static void readValues (int [] tab){
int i;
Scanner s = new Scanner ("Values.txt") ;
for(i=0; i<10; i++){
tab[i]=s.nextInt();
}
s.close();
}
Also there are many thing that will work in your code but is a bad practice or is not following conventions.
Variable names (e.g tab) should always be in camel case. It should only be a capital if it is a constant, which is not in your case.
The method names starts with small letter.
Also you are calling the two methods replaceOdd(TAB) and oddValues(TAB) But the return value is not being used anywhere.
FileNotFoundException will never be thrown
If you closely look at this method below
public static double oddValues(int[] TAB) {
int i;
double odd = 0;
int fn = 0;
for (i = 1; i < odd; i++) {
while (odd % 2 != 0) {
odd = fn;
}
break;
}
return fn;
}
The loop will never execute as odd is 0 so i<odd will always be false. Also the logic for odd is wrong.
public static int replaceOdd(int[] TAB){
int re=0;
for(int i=0; i<TAB.length; i++){
re = re/TAB.length;
}
return re;
}
This method will always return zero, the logic is wrong.
There are many more logical errors. I would suggest you to look into them as well

Related

How do I rearrange an integer so that it is rearranged as its highest possible value in Java? [duplicate]

This question already has answers here:
Scramble each digit of the int a and print out the biggest possible integer
(4 answers)
Closed 2 years ago.
For example, if someone inserts 34603, the output would be 64330. I've started this problem already but I can not think of a solution that works. Also, since this is an assignment, my instructor told me that arrays are not allowed. Here is what I have thus far:
public class loops{
loops(){}
public void biggest(int a){
String as = Integer.toString(a);
int index=0;
int asl = as.length();
while(index<asl){
String num1 = as.substring(index);
String num2 = as.substring((index+1));
int con1 = Integer.parseInt(num1);
int con2 = Integer.parseInt(num2);
if(con1<con2){
System.out.println("con2: "+con2);
}
if(con1>con2){
System.out.println("con1: "+con1);
}
System.out.println("added: "+con1+" "+con2);
index++;
}
}
public static void main(String []args){
loops x = new loops();
x.biggest(4583);
}
}
I would appreciate any and all help/hints, for I am truly lost on this one.
It should be reasonably obvious that the largest possible result is obtained by arranging the digits in descending order. One of the easier and more efficient ways of doing that would be with a counting sort, but the usual forms of that involve using arrays or array-equivalents to accumulate the counts.
So standard Counting Sort is out, along with all standard sort routines aimed at rearranging sequences of items. But you can still take your inspiration from Counting Sort. For example, figure out how many 9 digits are in the input, and form a number from that many 9s. Then figure out how many 8s and append them. Then how many 7s, etc. "Appending" digits to a number can be done arithmetically, so the whole procedure can be done without an array or array equivalent, even if we consider Strings to be array equivalents (as we should).
Details are left as the exercise they are intended to be.
I won't answer the question directly for you but suggest some ideas to help you.
you need to sort the integers in place - ie no arrays/no lists.. just iterate over the integer as a string which you're doing correctly, and progressively swap values so that you end up with a sorted numerical value.
thinking of various sort algorithms, quicksort, mergesort, bubble sort, etc. you effectively pick one of these algorithms and try to implement it.
start with the basic examples for integers to sort and iteratively develop your code to successively generate the correct answer... as test cases try:
no number at all... null
then the empty string ""
then a single digit, so a number 0-9
Next two digits both in order, then out of the sort order
then 3 digits in/out of order
Once you've implemented for 3 digits you should be able to generate your solution for any number of digits.
Note: if you use Integer as the input data type, you will be limited to being able to take a maximum integer value of Integer.MAX_VALUE (which isn't that large). Try to treat the input argument as a String and the individual digits as integers for the comparison (which you are already doing), this way you'll be able to process a much larger input.
import java.util.ArrayList;
import java.util.Collections;
public class loops{
loops(){}
public void biggest(int a){
String as = Integer.toString(a);
int index=0;
int index2=1;
int asl = as.length();
ArrayList<Integer> lista = new ArrayList<Integer>();
while(index<asl){
String num1 = as.substring(index,index2);
int con1 = Integer.parseInt(num1);
lista.add(con1);
index++;
index2++;
}
//order list
Collections.sort(lista);
Collections.reverse(lista);
System.out.println(lista);
//concatenate numbers
}
public static void main(String []args){
loops x = new loops();
x.biggest(34603);
}
}
**anything consult back. **
Ok, I came up with this. It's not the prettiest solution, I recognize that, but it DOES work. Have a look:
public class loops{
public int a,b,c,d,e,f,g,h,i,j;
public loops(){}
public void biggest(int a){
String as = Integer.toString(a);
int index=0;
a = 0;
b = 0;
c = 0;
d = 0;
e = 0;
f = 0;
g = 0;
h = 0;
i = 0;
j = 0;
int asl = as.length();
while(index<asl){
String num3 = as.substring(index,(index+1));
int con3 = Integer.parseInt(num3);
if(con3==9){a++;}
if(con3==8){b++;}
if(con3==7){c++;}
if(con3==6){d++;}
if(con3==5){e++;}
if(con3==4){f++;}
if(con3==3){g++;}
if(con3==2){h++;}
if(con3==1){i++;}
if(con3==0){j++;}
index++;
}
for(int z=0;z<a;z++){
System.out.print("9");
}
for(int y=0;y<b;y++){
System.out.print("8");
}
for(int x=0;x<c;x++){
System.out.print("7");
}
for(int w=0;w<d;w++){
System.out.print("6");
}
for(int v=0;v<e;v++){
System.out.print("5");
}
for(int u=0;u<f;u++){
System.out.print("4");
}
for(int t=0;t<g;t++){
System.out.print("3");
}
for(int s=0;s<h;s++){
System.out.print("2");
}
for(int r=0;r<i;r++){
System.out.print("1");
}
for(int q=0;q<j;q++){
System.out.print("0");
}
public static void main(String []args){
loops x = new loops();
x.biggest(45683408);
}
}
If arrays aren't allowed, then I don't think strings should be allowed either:
static void biggest(int n)
{
long counts=0;
for(; n>0; n/=10)
{
counts += 1L<<((n%10)*4);
}
long result=0;
for (long digit=9; digit>=0; --digit)
{
for(long rep=(counts>>(digit*4))&15; rep>0; --rep)
{
result = result*10 + digit;
}
}
System.out.println(result);
}

Calling method from another class that's an array

I am calling a method from another class. The method contains an integer array. I am trying to stay away from inputting the index manually.
I am trying to search for numbers within a range.
example:
ArrayList: {1,5}, {5,10}, {10,15}
Input: enter 3
Process: search for number within range
output: 1,5
The driver class is storing the objects from the main class called Numbers into ArrayList. The main class have an accessor call getNumbers. getNumbers contains an integer array with 2 elements. The driver is calling getNumbers to validate the entry that users input.
The code below works but I'm told it's consider bad coding to code entering the indexes. I want to know how to output the array from getNumber method without knowing the array length of getNumber?
example of what I have:
for(int i = 0; i < example.size(); i++)
//number is the integer that is inputted.
if(example.get(i).getNumbers()[1] > number &&
example.get(i).getNumbers()[0] <= numbers)
System.out.println(example.get(i));
Should I add another for loop?
example of what I am thinking of:
for(int i = 0; i < example.size(); i++)
for(int j = 0; j < example.get(i).getNumbers.length; j++){
if(example.get(i).getNumbers()[j] > number &&
example.get(i).getNumbers()[j] <= numbers)
System.out.println(example.get(i));
}
}
Edit: Changed how I worded some things and fixed the code of what I think I should do.
The code below works but I'm told it's consider bad coding to code
entering the indexes. I want to know how to output the array from
getNumber method without knowing the array length of getNumber ?
If you don't want to do the validations with array indexes for your first element and second element in the array, then you can solve the problem by modifying your Numbers class as shown below:
(1) Define two int variable members (currently you have only one)
(2) Add a method isInLimits(int input) to validate the range
(3) Override toString() which can be used to print the object as String
Numbers class (modified):
public static class Numbers {
private int firstElement;
private int secondElement;
public int getFirstElement() {
return firstElement;
}
public void setFirstElement(int firstElement) {
this.firstElement = firstElement;
}
public int getSecondElement() {
return secondElement;
}
public void setSecondElement(int secondElement) {
this.secondElement = secondElement;
}
//checks the input is in the range of this object elements
public boolean isInLimits(int input) {
if(input >= firstElement && input < secondElement) {
return true;
} else {
return false;
}
}
#Override
public String toString() {
return "{"+firstElement+","+secondElement+"}";
}
}
Usage of Numbers Class:
public static void main(String[] args) {
int userInput = 10; //get it from user
List<Numbers> example = new ArrayList<>();
//Add Numbers objects to example list
for(int i=0;i< example.size();i++) {
Number numberTemp = example.get(i);
//call Numbers object's isInLimits
if(numberTemp.isInLimits(userInput)) {
System.out.println(numberTemp);
}
}
}

how i can optimize this java code?

In below code string is passed in a method with numbers separated by space,
now we need to provide sum of smallest two numbers in the string.
public class SumNearZero {
public static int SumNearZero(String s) {
String temp=s;
int t1=0;
for (int i = 0; i <s.length(); i++) {
if(temp.contains(" "))
{
t1++;
temp=temp.substring(temp.indexOf(" ")+1);
}
}
int a[]=new int[++t1];
int index=0;
for(int i=0; i<s.length(); i++)
{
if(s.contains(" "))
{
a[index]=Integer.parseInt(s.substring(0,s.indexOf(" ")));
s=s.substring(s.indexOf(" ")+1);
index++;
}
}
a[index]=Integer.parseInt(s);
for (int i = 0; i < a.length; i++) {
for(int j=0; j<a.length-1; j++)
{
int c=a[j],n=a[j+1];
if(c>n)
{
int t=c;
a[j]=n;
a[j+1]=t;
} } }
int result=a.length>1 ? a[0]+a[1]:a[0];
return result;
}
public static void main(String[] args) {
System.out.println(SumNearZero("35 96 10 20 5"));
}
}
Above code is working fine but i want to reduce the code. if you provide some suggestion regarding this, I'll be happy to learn from you.
Restrictions : use of Collections, predefined methods e.g(String.split(),Arrays.sort()...)
I would suggest you not perform your calculation and display in a constructor, create a static method and invoke it. Next, in that method, create a List of Integer by iterating the substrings generated by splitting your input on one (or more) white space characters. Then, sort the List. Finally, return the sum of the first two elements1. It's also a good to do some error checking for one number (or no numbers). That might look something like
public static int sumNearZero(String s) {
List<Integer> al = new ArrayList<>();
for (String str : s.split("\\s+")) {
al.add(Integer.parseInt(str));
}
if (al.isEmpty()) {
return 0;
}
Collections.sort(al);
if (al.size() == 1) {
return al.get(0);
}
return (al.get(0) + al.get(1));
}
Then invoke it like
public static void main(String[] args) {
System.out.println(sumNearZero("35 96 10 20 5"));
}
I get (as I expected)
15
1once sorted the first two are the minimum, and the last two are the maximum
You can make it faster by using for each loop instead of for loop every time, it is more recommended and faster approach whenever loop is increasing for array, lists etc.
Plus more you can get all numbers in string by using split function which retrives you array of those numbers.and then you can put your logic for getting small numbers.this will reduce counting and increase speed highly in general if you want to learn about optimization then this is definitive guide i suggest you to go through it. and see this answer.
Looks like an exercise, so not giving actual code.
Use String.split and Arrays.sort

How do I fill an array in my main class with a fillPermutation void method?

My RandomPermutation class and fillPermutation method:
public class RandomPermutation
{
public int permutation[];
private int numAttempts[];
public void fillPermutation(int numItems, int seed)
{
if (permutation.length!=numItems)
permutation = new int[numItems];
Random rand = new Random(seed);
permutation[0]=rand.nextInt(numItems-1);
numAttempts[0]=1;
for(int i=1; i<numItems-1; i++)
{
int count = 0;
int m=rand.nextInt(numItems);
for(int j=0; j<i-1; j++)
while(m==permutation[j])
{
m=rand.nextInt(numItems);
count++;
}
permutation[i]=m;
numAttempts[i]=count;
}
}
}
Requirements for the main class:
"Initially, main-function should call fill-function once for numItems = 10, and print the permutation and the numAt- tempts as shown below. You would also want to print the integers m as they are created in the process, but turn the printing of m off before generating the second part of the output; save the outputs in some file. Then, add the call averNumAttempts with numItems = 10 and numIterationss = 100000 in main-function to generate the second part of the output and save it at the end of the first output file. Finally, submit paper copy of your code and the output file."
So how do I make this work using a void method? There's a bit more info on the assignment sheet about the other parts of the code if anybody needs clarification.
Thanks ahead of time!

Fibonacci Sequence return argument

I need to generate a program that generates the Fibonacci Sequence
Here is what I have so far:
import java.util.Scanner;
public class FibonacciRunner
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter n:");
int n = in.nextInt();
EP64 fg = new EP64();
for (int i = 1; i <= n; i++)
System.out.println(fg.nextNumber());
}
}
public class EP64
{
public static void nextNumber(int n)
{
int fold1 = 1;
int fold2 = 1;
int fnew = fold1 + fold2;
fold1 = fnew;
}
}
I get an error on:
System.out.println(fg.nextNumber());
saying:
method nextNumber in class EP64 cannot be applied to given types:
required: int
found: no arguments
reason: actual and formal argument lists differ in length
and can someone also tell me if I am doing this program right? If not, help! I looked at other similar questions but I cannot make much sense of them
Thank you all!
method nextNumber in class EP64 cannot be applied to given types: required: int found: no arguments reason: actual and formal argument lists differ in length
Your
public static void nextNumber(int n)
^^^^^^^
says that any call to the method must provide an integer as argument. But here:
System.out.println(fg.nextNumber());
^^ you need to add an integer argument
you violate this by providing no argument.
As your code reads now, I'd probably drop the int n argument.
and can someone also tell me if I am doing this program right?
Naah, not really...
fold1 and fold2 should probably be member variables (so they don't get reset in every call to the method),
You're forgetting to update fold2 (you only update fold1),
Also, you probably want to return an int from the nextNumber method.
Read up on
Official Java Tutorial: Defining Methods
You are calling a static method to a object reference instead of the class itself.
And
Not passing any argument at all for nextNumber() method.
Make the method non-static as :
public void nextNumber(int n) {}
Pass arg to the method as :
for (int i = 1; i <= n; i++)
System.out.println(fg.nextNumber(n));
And also don't forget to return the processed number from your nextNumber method,which you collecting in System.out.println.
Your declaration of nextNumber says it takes an int argument, but you are calling it with no arguments.
Also, your code isn't going to do what you want. You probably should make fold1 and fold2 members of class EP64 and make the method an instance method rather than a static method. You also need to do fold2 = fold1; before you update fold1.
Finally, you need to declare nextNumber to return an int value, and then actually have it return an int value.
You have two problems. Firstly, your method doesn't return anything, i.e. it is void. You need to make it int and add a return fnew; at the end. The other problem is you are starting from scratch every time, it will return 2 each time. You need to make fold1 and fold2 fields by moving them above the nextNumber line. Oh, and drop the int n argument as it doesn't do anything.
I agree on the diagnostics of the other posts, but don't suggest a member variable, but a rename and local variables.
You can ask for the 5th Fibonacci-Number with 5 calls to
fib.next ();
or with a single call to
fib (5);
Since the fibonacci-sequence increases very rapidly, you have very few calls (54) before hitting the overflow boundary. So if you repeatedly recalc the same sequence, to print the sequence, it's not a big problem. A recursive solution would be fine.
Btw.: EP64 is a very bad name.
I think this is enough:
import java.util.Scanner;
public class Fibnocci
{
public static void main(String []abc)
{
int a=0,b=1,c;
Scanner in=new Scanner(System.in);
System.out.print("Enter the Range: ");
int n= in.nextInt();
System.out.print(a+" "+b);
for(int i=0;i<n-2;i++) //n-2 because we are showing 0,1 initially.
{
c=a+b;
System.out.print(" "+c);
a=b;
b=c;
}
}
}
If you want to call this as a method then:
import java.util.Scanner;
public class Fibnocci
{
public static void main(String []abc)
{
Scanner in=new Scanner(System.in);
System.out.print("Enter the Range: ");
int n= in.nextInt();
callFibonocci(n);
}
public static void callFibonocci(int n)
{
int a=0,b=1,c;
System.out.print(a+" "+b);
for(int i=0;i<n-2;i++) //n-2 because we are showing 0,1 initially.
{
c=a+b;
System.out.print(" "+c);
a=b;
b=c;
}
}
}
You can call this method out of the class;
// Fibnocci Using c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeProject
{
class FibnocciSeries
{
public int[] FibonacciArray(int length)
{
int[] fseries = new int[length];
fseries[0] = 0;
fseries[1] = 1;
if (length == 0)
return null;
//Iterating through the loup to add adjacent numbers and create the memeber of series
for (int i = 2; i < length; i++)
{
fseries[i] = fseries[i - 1] + fseries[i - 2];
}
return fseries;
}
}
}
////////////////////
class Program
{
static void Main(string[] args)
{
FibnocciSeries fb = new FibnocciSeries();
Console.WriteLine("Please Enter Integer Length of Fibnocci series");
int length = Convert.ToInt32(Console.ReadLine());
int[] result = fb.FibonacciArray(length);
foreach(int i in result)
Console.Write(i.ToString()+ " ");
Console.ReadLine();
}
}
|

Categories