How to use scanner to input into a 2 dimensional array? - arrays

I'm taking a online Java course and attempting my 2nd assignment. The first assignment was not difficult but this one is just way over top. I honestly don't know where to begin. The problem is this class is online, basic instructions are to read these chapters and then write the program. There's not much guidance since my instructor is not with me physically.
I've never used scanner before or created two dimensional arrays. My instructor gives notes on what to do in each area of his skeleton program but I don't have a clue which one to start with.
Your task is to implement a similar scheme to store poynomials of any number of terms, such that the
number of terms and the components (coefficient, variable and exponent) of every term are entered from
the keyboard.
To implement the interactive input we will using the Java class Scanner, defined in the java.utils
standard package. The Scanner class can be used in Java to read data types from a file. Since the input
console (keyboard) is treated as the file called System.in, we can create a Scanner for that input stream
as new Scanner (System.in), as shown below. Once you define a Scanner object, using its method
next() you can read Strings from the file/keyboard.
The incomplete program below is your assignment. You are supposed to complete without changing the
existing code.
Your output should be the terms of the polynomial entered by the user, separated by + signs.
Additional instructions in the code below, that you will change to achieve the requested functionality.
import java.util.Scanner;
public class Polynomials {
public static void storeTerm (int coeff, String var, int exp, String poly[][], int
where){
//ENTER THE COEFFICIENT, VARIABLE AND EXPONENT INTO THE
//ARRAY POLY THAT REPRESENTS THE POLYNOMIAL, AT POSITION "where"
//THAT RANGES BETWEEN INDEX 0 AND POLY.LENGTH-1
}
public static void printTerm (String [] term) {
//PRINTS EACH TERM
//IF THE EXPONENT OF THE VARIABLE IS 1 DOE NOT PRINT THE EXPONENT
//IF THE EXPONENT IS 0, PRINT ONLY THE COEFFCIENT
//IF THE COEFFICIENT IS 1, DO NOT PRINT IT, UNLESS IT IS THE ONLY COMPONENT OF
//THE TERM
}
public static void printPolynomial(String terms[][]){
//CALL printTerm in a loop to print all terms separated by + signs
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int numberTerms = 0;
System.out.println("How many terms?");
numberTerms = sc.nextInt();
//ENTER HERE THE CODE TO CREATE THE TWO DIMENSIONAL ARRAY NEEDED TO STORE THE TERMS
//OF THE POLYNOMIAL
if (numberTerms <= 0)
System.out.println("Error: Polynomials must have at least one term");
else {
String coeff = "", variable="", exponent="";
for (int i = 1; i<= numberTerms; i++) {
System.out.println("Enter the coeffcient for term " + i);
coeff = sc.next();
System.out.println("Enter the variable name:");
variable = sc.next();
System.out.println("Enter the expoenent for this term");
exponent = sc.next();
//CALL METHOD storeTerm TO INPUT THIS NEW TERM INTO THE ARRAY WRITE THE CORRECT
//CALL TO storeTerm HERE
}
printPolynomial(terms);
}//endf if
}//end main
}//end class
Again not looking for answers. Just where to start. Then I'll post my results.

It is not completely obvious where the two-dimensional array enters, since the structure hints at a list of terms.
You will need to define a data structure, in Java as a class, to hold the information for each term.
From the description, it seems that the input are polynomials of the form 3x^2+5y^7 and not xy+3y^2z^3.

Related

How would I convert the data type int[] to the data type int

I have set up an array to randomize 5 different numbers in one class. In a different class I have prompted a user to guess the random number, and must reference the number each time to determine whether they have guessed correctly or not. My issue is that the numbers being randomized are in the data type int[], and I need to compare them to the data type int. When trying to reference the randomized numbers I get the error "Type mismatch: cannot convert from int[] to int". Any advice on how I would do that?
Class diceNumGen
final static int ARRAY_SIZE = 5;
public static int[] randNumArray = new int [ARRAY_SIZE];
public static int[] randNums(){
for(int i=0; i < randNumArray.length; i++) {
randNumArray[i] = (int) (Math.random()*12);
System.out.println(randNumArray);
}
return randNumArray.clone();
}}
Class Bet
static Bet bet = new Bet();
diceNumGen newClassObj = new diceNumGen();
int secondArray = diceNumGen.randNumArray;
//Set Turns variable where turns = 5
public int turnsToGo = 5;
//Set up the bet() method
public void bet() {
//Sets up the options as an array to be on the JOptionPane, each are numbered 0, 1, and 2 respectively
String[] options = {"Guess below 7", "Guess 7", "Guess above 7"};
welcome here, I'm newcomer too, this is my first answer.
I assume that you are using java, because of keywords, it is good to define the programming language in the question or tags to get better responses.
the first thing about your code is you don't need a whole class for generating an array, an ordinary function like this would be OK too:
static int[] randomGen(int len){
java.util.Random rand = new java.util.Random();
int[] randoms = new int[len];
for (int i = 0; i < len; i++) {
randoms[i] = rand.nextInt(12);
}
return randoms;
}
the next thing is, please indent your code, un-indented code (or badly indented code) will confuse the reader.
and about your question, at the first point why are you creating random array with the size of 5? if you just need one random number, just create one random number (with your Math.random() or better, nextInt(12) in Random class)
if user have 5 chances to guess same number you don't need 5 random numbers. just use this:
int randomNumber = (int) (Math.random() * 12);
or if you want user to guess 5 separate numbers, you need a for loop to iterate this random array per user guess.
Good luck in learning java.

I am getting the error "bad operand types for binary operator '+' and I don't know how to fix it

This code is going to do the Fibonacci series but with a dynamic array. I am a beginner with programming so if there is anything else wrong with my code, feel free to correct it.
public class FibonacciDynamic
{
public static void main(String[] args)
{
int[] numbers;
int[] x;
numbers = new int[x+1]; //This is where bad operand is coming from
numbers[0]=0;
numbers[1]=1;
System.out.println("\n Fibonacci series: \n");
System.out.println(numbers[0]);
for (int i=2; i<x+1; i++)
{
numbers[i]=numbers[i-2]+numbers[i-1];
System.out.println(numbers[x]);
}
}
}
Error -
bad operand types for binary operator '+'
first type: int[]; second type: int
The problem is that the two values you are trying to add together are not the same type and java does not understand what it means to add them together. The reason this is happening is because arrays are objects in Java, and all objects live on the Heap (in memory). Therefore, x is not an integer, but rather it is a memory location. Some hexadecimal value like 0xf6434. Java could interpret that as an integer, but for type safety it throws an error and forces you to handle it.
So what are you trying to do with this statement: numbers = new int[x+1]?
Are you trying to create an array called numbers that is bigger then the array x by 1? in order for this to work your code should look like this: numbers = new int[x.length+1]; Furthermore, you must initialize x to point to an array with some size. Currently, the variable x is simply a pointer on your call stack which is not pointing towards any object (specifically an array).

Get sets of six unique combinations from an array given the range

I do have a problem, i have numbers from 1-49, now the question here is how do i get the maximum number of random sets of six from the given sample. like
int[] a1 = { 1, 2, 3 ,5,6,7 ... 49};
how many unique combination of numbers or arrays can i get from that one big array from 1 to 49 like below
1,2,3,4,5,6
2,1,4,5,8,9
2,1,0,2,4,5
................
What am trying to get is the maximum output or number of possible unique arrays with a length of six i could get . to be honest i have tried writing a loop that reads through the array, but how to capture six random digits is where am stuck i can go any further than
for(int x=0;<a1.length;x++)
{
// here i believe i must turn the captured information
// into a muti dimentional array to cpature like '1,2,3,4,5,6' but how. am stuck
}
If I understand your question correctly, what you need is the binomial coefficient n! / k! (n - k)!, which in this case would be 49! / (6! * (49 - 6)!) = 13983816. No need to write code if the only thing you want to know is the number of possible combinations.
If you really wanted to list all of them, you'd need a little patience. One way to achieve this is via a recursive approach:
public class NOverK {
private static final int[] numbers = new int[6];
private static final int MAX = 49;
private static void output() {
System.out.println();
for (int n : numbers) {
System.out.print(n + " ");
}
}
private static void allCombinations(int x, int start) {
if (x > 0) {
for (int i = start; i <= MAX; i++) {
numbers[numbers.length - x] = i;
allCombinations(x - 1, i + 1);
}
} else {
output();
}
}
public static void main(String[] args) {
allCombinations(6, 1);
}
}
This question has been asked at Stack Overflow a few times in the past. For example, look at this answer:
Click here: Algorithm to return all combinations of k elements from n
The answers to this question contain numerous solutions of your question in different programming languages (Java, Python, C, C# etc.), too. Check out or adjust a solution that meets your requirements.
You can search for other questions/answers in Stack Overflow (search field in upper right corner) with keywords
[algorithm] [combinations]
A Google search would lead to numerous solutions of your question, too. Try with keywords as follows:
java algorithm combinations without repetition
or
c# algorithm combinations without repetition

Having trouble parsing multiple files and storing in array in Java

I'm attempting to create a class that takes a certain number of ppm files that are formatted identically (which are input by the user in the class containing the main method), and then compares the corresponding integers in each file one by one, storing them in a temporary array so that they can be sorted and the median can be taken and written to a new ppm file ultimately creating a new image.
For example, if I had 3 files I would want to take the first integer value (after the 3 lines of the header) of each one, storing each value in the temporary array (in this case of size 3) for comparison and then I would want to do the same thing with the second value in each file, and the third, etc. This is what I'm stuck on. Right now the way that I have it set up is leading to a null pointer exception but I've tried various other things that have ran but led to the incorrect result. Any advice?
import java.io.File;
import java.io.IOException;
//import java.io.PrintWriter;
import java.util.Scanner;
import java.util.Arrays;
public class Effects {
public Effects() throws IOException{}
public void filter(File[] files, String outputFileName) throws IOException {
//Create an array of Scanners equal to the number of files
Scanner[] scanner = new Scanner[files.length];
//Create a scanner that is linked to each file that must be read
for(int i=0; i<scanner.length; i++) {
Scanner scan = new Scanner(files[i]);
scanner[i]=scan;
//For each scanner, first skip the first 3 lines of text, then take one integer from
//file and store it in the temporary array compare [such that the integer parsed
// by scanner[0] is stored at compare[0] and so on.
while(scan.hasNext()) {
int [] compare = new int [scanner.length-1];
boolean header = true;
for(int j=0; j<files.length; j++) {
while(header==true) {
//the first 3 lines in each document need to be skipped before the integer values of relevance begin.
scanner[j].nextLine();
scanner[j].nextLine();
scanner[j].nextLine();
header = false;
}
int value = scanner[j].nextInt(); //NULL POINTER EXCEPTION
compare[j] = value;
}
}
}
}
}
The reason you're seeing the NPE is that the j=1 code runs before i=1 and therefore scanner[1] doesn't exist yet.
It might be a good idea to handle reading each file separately and combining the values later. That would also split your reading code from your calculations, making it easier to track down any future bugs.

How do i keep my program going?

Hey guys im making a game to help me study for finals. It is basically flash cards. I want the program to print out my question and answer by randomly selecting one. The thing is i dont want he same random number to be picked twice. how do i make sure the same number isn't picked twice till im out of questions? I am trying to make each random number be stored in blacklist so i can just check if the number is already in there before the program prints.
import java.util.ArrayList;
import java.util.Random;
public class Games {
static ArrayList<Integer> blacklist = new ArrayList<Integer>();
static int number;
static String[][] yes = {{"Apostolic Orgin", "Comes form the apostles"},
{"Biblical inerrancy", "the doctrine that the books are free from error reading the truth"},
{"Divine Inspiration", "the assistance the holy spirit gave the authors or the bible so they could write"},
{"fundamentalist approach", "interpretation of the bible and christian doctrine based on the literal meaning og bible's word"}, {"pentateuch", "first 5 books of old testament"}};
public static void main(String[] args) {
Printer(pickQuestion(), pickAnswer());
}
public static int RandomNumber(int i) {
int c;
Random r = new Random();
c = r.nextInt(i);
return c;
}
public static void Printer(String question, String answer) {
System.out.println("Question: " + question);
System.out.println("Answer: " + answer);
}
public static String pickQuestion() {
number = RandomNumber(yes.length);
return yes[number][0];
}
public static String pickAnswer() {
return yes[number][1];
}
}
The easiest option is to pre-shuffle the list of questions, either messing with the question and answer arrays directly, or by creating an array of integers from 1 to n where is the number of questions, shuffling that, and then loading the "card" in the position pointed to by that value in the array.
That is, create
[1,2,3,4,5]
Shuffle:
[5,1,3,4,2]
And load question 5, then question 1, etc.
This latter option would make a few things easier, not least of which is debugging!
Creating the array in order is a trivial for loop, and there are plenty of standard algorithms for shuffling too.
Random shuffling of an array

Resources