I am pretty new at Java and I am finding difficulty in solving the problem. Basically the code get a number, and generate a vector in the function generateVector. When I run this code, I am asked to put a number and then the software stay running forever. If possible, could you guys help me without other functions that is kind advanced? I am still learning. Thanks.
import java.util.Scanner;
public class Atividade02 {
static Scanner dados = new Scanner(System.in);
static int n;
//Main
public static void main(String args[]){
System.out.println("Type a number: ");
n = dados.nextInt();
int[] VetorA = generateVector(n);
for(int i=0; i<VetorA.length; i++){
System.out.println("Position: "+ VetorA[i]);
}
}
//Função
public static int[] generateVector(int n){
int[] VetorA = new int [n];
for (int i=0; i<n; i++){
VetorA[i] = dados.nextInt();
}
return VetorA;
}
}
I am asked to put a number and then the software stay running forever.
Did you enter in the n numbers required by generateVector? The program is probably just blocked on input from the user.
Try to modfiy the class as follows:
import java.util.Scanner;
public class Atividade02 {
// Added private access modifiers for properties.
// It's not necessary here, but as a general rule, try to not allow direct access to
// class properties when possible.
// Use accessor methods instead, it's a good habit
private static Scanner dados = new Scanner(System.in);
private static int n = 0;
// Main
public static void main(String args[]){
// Ask for vector size
System.out.print("Define vector size: ");
n = dados.nextInt();
// Make some space
System.out.println();
// Changed the method signature, since n it's declared
// as a class (static) property it is visible in every method of this class
int[] vetorA = generateVector();
// Make some other space
System.out.println();
// Show results
for (int i = 0; i < vetorA.length; i++){
System.out.println("Number "+ vetorA[i] +" has Position: "+ i);
}
}
// The method is intended for internal use
// So you can keep this private too.
private static int[] generateVector(){
int[] vetorA = new int[n];
for (int i = 0; i < n; i++) {
System.out.print("Insert a number into the vector: ");
vetorA[i] = dados.nextInt();
}
return vetorA;
}
}
Also when naming variables stick with the Java naming convention, only classes start with capital letters.
Related
So currently I am studying Arrays so I am new to this. I have created this code but when I try to enter my inputs after specifying the size it gives me the error java.lang.NullPointerException
I know one of the ways is to use constructors but I want to try it this way.
Also I know my print statements are not configured correctly but I can fix that later should be simple.
import java.util.Scanner;
public class CourseTest {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("Enter size of Course");
int x=s.nextInt();
Course arr[]=new Course[x];
Course c =new Course();
for (int i = 0; i < arr.length; i++) {
System.out.println("Enter Course Code");
arr[i].setCchour(s.nextInt());
System.out.println("Enter course Title");
arr[i].setCtitle(s.next());
System.out.println("Enter Course Credit hour");
arr[i].setCchour(s.nextInt());
}
for (int i = 0; i < arr.length; i++) {
System.out.println("Course Code is");
System.out.println(arr[i]);
System.out.println("Course Title is");
System.out.println(arr[i]);
System.out.println("Course Credit hour is");
System.out.println(arr[i]);
}
}
}
"Class"
public class Course {
private int Ccode;
private String Ctitle;
private int Cchour;
public void setCcode(int Ccode) {
this.Ccode = Ccode;
}
public void setCtitle(String Ctitle) {
this.Ctitle = Ctitle;
}
public void setCchour(int Cchour) {
this.Cchour = Cchour;
}
public int getCcode() {
return Ccode;
}
public String getCtitle() {
return Ctitle;
}
public int getCchour() {
return Cchour;
}
}
Course arr[]=new Course[x];
Okay, you now have an array that can hold references (pointers) to course objects. It's like you've created a book where on each page you can write the details of a course, but the pages are still blank. It has x pages.
Course c =new Course();
Okay, you have created a new course object, and you have created a new variable named c which can reference (point at) course objects; c now points at the created course.
You never use c again, so this line does nothing.
arr[i].setCchour(s.nextInt());
okay, you flip to the first page of your book and,.. oh dear, it is blank, so, NullPointerException.
Solution
learn about how java works, what references are. Then it becomes obvious: That Course c = new Course(); line doesn't do anything; you want 1 course for each 'page' in your book-of-courses (your array), so new Course() needs to run x times. That suggests, correctly, that it needs be inside the for loop. First action in that for loop should be arr[i] = new Course(). Meaning: Create a new course object. Write the reference to this newly created object on the i-th page of your book of courses.
The assignment states that there's another class that will call this class. It is similar to betting - you select 12 characters and put them in the array and the program will output a random set of characters. Then it will calculate how many of those matched.
The teacher told me that there should be a parameter of char[] type in the print() method and two in the checked method, but I don't understand the need for them. I could make something similar without his weird choices, but I'm stuck with that. Therefore, I am wondering, if anyone understands the reason for that. It is a method for user input already and it is a method for the computer generated randoms, so I don't see why I have to put a parameter on the other methods. Can't see how that is a logical choice.
Code to solve the assignment:
import java.util.Random;
import java.util.Scanner;
import java.util.Arrays;
public class Tipping
{
char[] ukensRekke;
public Tipping()
{
ukensRekke = new char[12];
}
public void WeekResult(){
String HBU = "HBU";
for(int i = 0; i < ukensRekke.length; i++){
ukensRekke[i] = HBU.charAt((int)(Math.random()*3));
}
}
public char[] getWeekResult(){
return ukensRekke;
}
public void print(char[] tastet){
tastet = new char[12];
for(int i = 0; i < tastet.length; i++){
System.out.print(tastet[i]);
}
}
public char[] register(){
Scanner scan = new Scanner(System.in);
char[] vinnerTall = new char[12];
for(int i = 0; i < vinnerTall.length; i++){
System.out.println("Skriv inn H,B eller U for kamp" + (i+1) + "; ");
vinnerTall[i] =scan.next().charAt(0);
System.out.println(vinnerTall[i]);
}
return vinnerTall;
}
public int check(char[] original, char[] tastet){
original = ukensRekke;
tastet = register();
return tastet.length;
}
}
UPDATE: Hi, so I was somewhat able to solve the problem, but it's still one finishing touch. Here's the part of the code I have problems with, hope someone can help me out.
System.out.println("Klassen Tipping instansieres...");
System.out.println();
System.out.println("Ukens rekke genereres...");
System.out.println();
System.out.println("Brukers rekke registreres.");
tp.register();
System.out.println();
System.out.println("Ukens rekke hentes...");
System.out.println();
System.out.println("Ukens rekke;");
tp.print(tp.getWeekResult());
System.out.println("Brukers rekke;");
tp.print(tp.register());
System.out.println();
System.out.println("Bruker hadde" + tp.check(tp.getWeekResult(),tp.register()) + "riktige tippetanger");
this is the class that I use to make a kinda like sheet, it prints out everything on the screen and takes the user input, but the last two method calls doesn't work, the program just skips it and starts all over again.
and this is the code I use that gets called from:
public void WeekResult(){
String HBU = "HBU";
for(int i = 0; i < ukensRekke.length; i++){
ukensRekke[i] = HBU.charAt((int)(Math.random()*3));
}
}
public char[] getWeekResult(){
return ukensRekke;
}
public void print(char[] tastet){
System.out.print(taste);
}
public char[] register(){
Scanner scan = new Scanner(System.in);
char[] vinnerTall = new char[12];
for(int i = 0; i < vinnerTall.length; i++){
System.out.println("Skriv inn H,B eller U for kamp" + "; ");
vinnerTall[i] = scan.next().charAt(0);
}
return vinnerTall;
}
Your teacher asks you to use a char[] array over a String object simply to use less memory.
Read the answer(s) to this question: How much memory does a string use in Java 8?
One of the answer shows that a String object takes up a minimum of 80 (-8) bytes in memory. In your case, the char array ukensRekke needs only 12 * 2 = 24 bytes. So less memory is used. This is a good advice. You should always keep these efficiency factors in mind to be able to make efficient programs.
public class Alfabhto {
int[][] pinakas = new int[3][6];
String[] gramata ={"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter an alphanumeric combination");
String fail = s.nextLine();
System.out.println(pinakas[i][j]);
}
public int[][] Numbers() {
Random rand = new Random();
for (int i=0;i<3;i++)
{
for (int j=0;j<6;j++)
{
pinakas[i][j] = rand.nextInt(38)-12;
}
}
return pinakas;
}
}
First of all, I am very new at java. The main function works properly and the user is asked to give an input. Some elements aren't used here (like the gramata array) so ignore them.
The problem is: the method numbers should fill the pinakas array with random numbers and then print them. It does nothing if it's in the method. Outside it brings up errors because it can't get "pinakas" array or i and j. Any ideas?
There is several issues with that code, see comments:
// Need to import Random
import java.util.Random;
public class Alfabhto {
String[] gramata ={"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
// This neesd to be final for Numbers to access it
final int[][] pinakas = new int[3][6];
// There's no reason for Numbers to be public, or to extend Alfabhto, or in
// fact to be a class at all. Recommend making it a static method within
// Alfabhto (in which case gramata and pinakas must also be static), or an
// instance method if appropriate (in which case pinaka does not need to be
// final anymore, though you might leave it that way if you never
// intend to replace the array with a different one.
// Also recommend making that method (static or instance) a private method.
public class Numbers extends Alfabhto {
public Numbers() {
// Create this once and reuse it
Random rand = new Random();
// Note using <, not <=, on the loops
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 6; j++) {
pinakas[i][j] = rand.nextInt(38) - 12;
System.out.println(pinakas[i][j]);
}
}
}
}
// Since Numbers is an inner class, we need to be able to create instances of Alfabhto
private Alfabhto() {
}
// We need something in Alfabhto to run the Numbers constructor
private void run() {
// Run the code in the Numbers constructor
new Numbers();
}
public static void main(String[] args) {
/* None of this does anything, presumably you'll use it later...
Scanner s = new Scanner(System.in);
System.out.println("Enter an alphanumeric combination");
String fail = s.nextLine();
*/
// Run our run method, which will run the code in the Numbers constructor
new Alfabhto().run();
}
}
In your main function, you never create an instance of Numbers so whatever your wrote in there is not being called. Once you create a new Numbers(), it should print something out.
I am trying to build a program that reads in info from a .txt file, which contains 20 individuals. Each person has four fields, the team they belong to, their batting average, and home run totals. I need to add each individual to their team(4 players to each team), total up the team home run totals, and rank the 5 teams in order.
I am able to read the text in properly to a single array, consisting of each individual, but I cannot figure out how to also use this data to create a 2D Array. Using the 2D array I would, put the players on the correct teams, and add their home run totals. I want to sort the home run totals from greatest to smallest for each team, and each individual. I am have done my best to find answers, and to learn on other posts and sites, but I am just stumped with the concept of creating 2D arrays and how to sort them.
Updated explanation:
This is what the info should look like for the single array:
[Team][Name][avg][Home Runs]
Then I JUST want to sort the [Home Runs] column, from greatest to smallest, but don't know how to just access that portion of the array.
The 2D array should look like this:
[Team] [Total Team Home Runs]
Once again, sorting from greatest to smallest.
Example of the .txt file looks like this:
Team: Name: Avg:HR:
MILRyan Braun .31015
STLMatt Adams .28718
PITSterling Marte .26420
CINJoey Votto .30224
CUBAnthony Rizzo .27422
PITAndrew McCutchen .29522
MILAdam Lind .28013
The following class reads in the .txt file and puts it in array.
public class ReadTxt {
static String[] teamm = new String[20];
static String[] name = new String[20];
static int[] avg = new int[20];
static double[] homeRuns = new double[20];
static String teams;
static int i;
public void Players(String[] teamm, String[] name, int[] avg, double[] homeRuns){
String[] team = new String[20];
File txtFile = new File("C:\\Users\\Users Name\\Desktop\\homerun.txt");
try{
Scanner txtScan = new Scanner(txtFile);
while(txtScan.hasNext()){
for(i = 0; i < 20; i++){
teams = txtScan.nextLine();
team[i] = teams;
}
}
}
catch(FileNotFoundException e){
System.out.println("File not found" + txtFile);
}
for (i = 0; i < team.length; i++){
System.out.println(team[i]);
}
}
}
The next class is my attempt at sorting:
public class Sort {
static String[] teamm = new String[20];
static String[] name = new String[20];
static int[] avg = new int[20];
static double[] homeRuns = new double[20];
private int index = 0;
private int US = 0;
static double[] homeRunArray;
public void Players(String[] teamm, String[] name, int[] avg, double[] homeRuns){
homeRunArray[index] = ReadTxt.homeRuns[index];
index++;;
US++;
}
public void selectionSort(){
double temp;
int min;
for(int i = 0; i < US-2; i++){
min = i;
for(int j=i+1; j<= US-1; j++){
if(min !=i){
temp = homeRunArray[i];
homeRunArray[i] = homeRunArray[min];
homeRunArray[min] = temp;
}
}
}
}
public void printArray(double[] homeRuns){
for(int i = 0; i < 20; i++){
System.out.print(homeRunArray[i]);
}
System.out.print("\n");
}
}
I don't get your question, but I think you are kind of stuck in your 2D-Array problem...
I would recommend you to create a class and implement Comparable (or use a Comparator). Something like the code below, or even better, make a real Player class. This is much easier to understand.
public class Sorter {
public static void main(String[] args) {
try {
Scanner scanner = new Scanner(new File("team"));
List<SortableLine> lines = new ArrayList<SortableLine>();
while(scanner.hasNext()) {
lines.add(new SortableLine(scanner.nextLine()));
}
Collections.sort(lines);
for(SortableLine line : lines) {
System.out.println(line.line);
}
} catch(FileNotFoundException e) {
System.err.println("File not found");
}
}
private static class SortableLine implements Comparable<SortableLine> {
private String sortCol;
private String line;
private SortableLine(String line) {
this.line = line;
this.sortCol = line.substring(24, 26);
}
public int compareTo(SortableLine other) {
return sortCol.compareTo(other.sortCol);
}
}
}
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();
}
}
|