I'm trying to build an Array with 5 strings in there; indexed 0 - 4. After this I need to shuffle the different pieces in the array rounds. The problem that I'm having is that is creating 5 different arrays I think? Could someone explain to me what I'm doing wrong and how to fix it?
To give an better understanding; this is the input of the fileScanner:
5,4 4,5 8,7=6,3 3,2 9,6 4,3=7,6=9,8=5,5 7,8 6,5 6,4
class Pirate {
public static final int MAX_ELEMENTS = 5;
String [] coordinateArray;
int position;
PrintStream out;
Pirate() {
out = new PrintStream(System.out);
}
void addInOrginalArray (String coordinateRowInput) {
coordinateArray = new String [MAX_ELEMENTS];
int position = 0;
coordinateArray[position] = coordinateRowInput;
for (int i = 0; i < coordinateArray.length; i++) {
position += 1;
System.out.println(i + "\t" + coordinateArray [i]);
}
}
void start() {
Scanner fileScanner = UIAuxiliaryMethods.askUserForInput().getScanner();
fileScanner.useDelimiter("=");
while (fileScanner.hasNext()) {
String coordinateRowInput = fileScanner.next();
Scanner coordinateInputScanner = new Scanner(coordinateRowInput);
addInOrginalArray(coordinateRowInput);
}
}
public static void main(String[] argv) {
new Pirate().start();
}
}
Related
Hey I'm trying to calculate the of a quiz by comparing two arrays. The two arrays set up are the correct answers and student answers of a quiz. I'm trying to get it to look like this:
Student Marks Average
Arnie Score: 4 Percentage: 0.8
This is because Arnie has got 4 questions correct out of 5 questions. The answers of the student and the correct answers are found in the text document which I already loaded onto an array on my code. The text document contains a 2D array with Arnie's answers in the form of chars and a 1D array containing the correct answers (also chars). There are more students but I would like some guidance on how to get the average for Arnie so I can do it for the rest of the names on my own.
Here is my code so far with the two arrays set up.
public class workingCode
{
private static String newline = System.getProperty("line.separator");
public static void stuAnsOut(String arg []) throws IOException
{
File studentAns = new File("Ans_Stu.txt");
Scanner stuAns = new Scanner(studentAns);
String stuAnsString[] = new String[6];
char stuAnsArray[][] = new char[3][5];
String[] stuNameArray = new String[3];
for (int i = 0; i<stuAnsString.length;i++)
{
stuAnsString[i]=stuAns.nextLine();
}
for (int i=0,j=0; i<stuAnsArray.length && j<stuAnsString.length;i++, j=j+2)
{
stuNameArray[i] = stuAnsString[j];
}
for (int i=0,j=1; i<stuAnsArray.length && j<stuAnsString.length;i++, j=j+2)
{
stuAnsArray[i] = stuAnsString[j].toUpperCase().toCharArray();
}
System.out.println("Student Answers: ");
System.out.printf("%5s","Name");
for (int i =0; i<1;i++)
{
for (int j =1; j<(stuAnsArray[i].length+1);j++)
{
System.out.printf("%5s",j);
}
}
System.out.printf("%n");
for (int i =0; i<stuAnsArray.length;i++)
{
System.out.printf("%5s",stuNameArray[i]);
for (int j=0;j<stuAnsArray[i].length;j++)
{
System.out.printf("%5s",stuAnsArray[i][j]);
}
System.out.printf("%n");
}
}
public static void corAnsOut(String arg []) throws IOException
{
File correctAns = new File("Ans_Cor.txt");
Scanner corAns = new Scanner(correctAns);
String corAnsString = corAns.next();
char corAnsArray[] = new char[5];
for (int i=0; i<corAnsArray.length;i++)
{
corAnsArray[i] = corAnsString.toUpperCase().charAt(i);
}
System.out.println("Correct Answers: ");
System.out.println(newline);
for (int i =1; i<(corAnsArray.length+1);i++)
{
System.out.printf("%5s",i);
}
System.out.printf("%n");
for (int i =0; i<corAnsArray.length;i++)
{
System.out.printf("%5s",corAnsArray[i]);
}
System.out.printf("%n");
}
}
I am not allowed to use ArrayLists, only Arrays. And please use the array names I already have in my code. Thanks!
Edit: This is what I got so far. But it is giving me an error:
public static void compareInteger(int corAnsArray [], int stuAnsArray[])
{double score =0;
for (int i = 0; i < stuAnsArray.length; i++)
{if(stuAnsArray[i] == corAnsArray[i])
score += 1.0;
}
System.out.println(score/corAnsArray.length);
}
What i would do is create a class called Student
public class Student {
private string studentName;
private float marks;
private float average;
// Getters & all parameter constructor
}
Then change your working class to
public class workingCode
{
private static String newline = System.getProperty("line.separator");
public static void stuAnsOut(String arg []) throws IOException
{
File studentAns = new File("Ans_Stu.txt");
Scanner stuAns = new Scanner(studentAns);
List<Student> students = new ArrayList<Student>();
while(stuAns.hasNext()) {
string parts = stuAns.nextLine().split(" ");
students.add(new Student(parts[0],parts[1],parts[2]))
}
// At this point you have all the students in the List
}
}
Now to calculate avg :
float total = 0;
for(Student s : students) {
total += s.getMarks();
}
System.out.println("avg = " + total/students.size());
or
float total = 0;
for(Student s : students) {
total += s.getAverage();
}
System.out.println("avg = " + total);
Code for comparing arrays (both for INT and String arrays):
public class Compare{
public static void main(String[] args){
double averageInt;
double averageString;
int[] correctInt = {9,8,12,6,3,12,90}; //Correct answers
int[] answerInt = {9,8,4,6,3,12,90}; //Student's answers
String[] correctString = {"A","A","B","C"}; //Correct answers
String[] answerString = {"A","C","B","C"}; //Student's answers
Compare compare = new Compare();
averageInt = compare.compareInteger(correctInt, answerInt);
averageString = compare.compareString(correctString, answerString);
System.out.println(averageInt);
System.out.println(averageString);
}
public double compareInteger(int[] correct, int[] answer){ //Compares the int arrays
double score = 0;
for(int i = 0; i < correct.length; i++){
if(correct[i] == answer[i])
score += 1.0;
}
return score/correct.length; //Returns average
}
public double compareString(String[] correct, String[] answer){ //Compares the String arrays
double score = 0;
for(int i = 0; i < correct.length; i++){
if(correct[i].equals(answer[i]))
score += 1.0;
}
return score/correct.length; //Returns average
}
}
I do not understand the marking system though. If you'd explain it more in-depth, I'd be more than happy to provide you with the code.
I need to create a JAVA method: public static int[] Numb() that reads and returns a series of positive integer values. If the user enters -1 we should stop accepting values, and then I want to call it in the main method. And we should return to the user integers that he entered them, with the total number.
So if he entered the following:
5 6 1 2 3 -1
So the total number is : 6
The numbers entered are: 5 6 1 2 3 -1
I tried the following:
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
}
public static int[] readNumbers(int[] n)
{
int[] a = new int[n.length];
Scanner scan = new Scanner(System.in);
for(int i = 0;i<n.length;i++) {
String token = scan.next();
a[i] = Integer.nextString();
}
}
}
And here is a fiddle of them. I have an error that said:
Main.java:21: error: cannot find symbol
a[i] = Integer.nextString();
I am solving this exercise step by step, and I am creating the method that reads integers. Any help is appreciated.
Integer.nextString() doesn't exist, to get the next entered integer value, you may change your loop to either :
for(int i = 0;i<n.length;i++) {
a[i] = scan.nextInt();
}
or as #vikingsteve suggested :
for(int i = 0;i<n.length;i++) {
String token = scan.next();
a[i] = Integer.parseInt(token);
}
public static void main(String[] args) {
List<Integer> numList = new ArrayList<>();
initializeList(numList);
System.out.println("Num of integer in list: "+numList.size());
}
public static void initializeList(List<Integer> numList) {
Scanner sc = new Scanner(System.in);
boolean flag = true;
while(flag) {
int num = sc.nextInt();
if(num==-1) {
flag = false;
}else {
numList.add(num);
}
}
sc.close();
}
Since the number of integers is unknown, use ArrayList. It's size can be altered unlike arrays.
You can create something like arraylist on your own..it can be done like this:
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
CustomArray c = new CustomArray(3);
boolean flag = true;
while (flag) {
int num = sc.nextInt();
if (num == -1) {
flag = false;
} else {
c.insert(num);
}
System.out.println(Arrays.toString(c.numList));
}
sc.close();
}
}
class CustomArray {
int[] numList;
int size; // size of numList[]
int numOfElements; // integers present in numList[]
public CustomArray(int size) {
// TODO Auto-generated constructor stub
numList = new int[size];
this.size = size;
numOfElements = 0;
}
void insert(int num) {
if (numOfElements < size) {
numList[numOfElements++] = num;
} else {
// list is full
size = size * 2; //double the size, you can use some other factor as well
//create a new list with new size
int[] newList = new int[size];
for (int i = 0; i < numOfElements; i++) {
//copy all the elements in new list
newList[i] = numList[i];
}
numList = newList;//make numList equal to new list
numList[numOfElements++] = num;
}
}
}
So I have been creating a Word-Puzzle which I recently got stuck on a index out of bounds problem. This has been resolved however the program is not doing what I would like it to do. The Idea i that the test class will print 3 words in an array e.g. [FEN, GNU, NOB] (and yes they are apparently real english words). Then check to see if the first letter of each word combined is a word and so forth e.g. FGN if so add it to the next ArrayList else start again. Ideal output would be [FEN, GNU, NOB] [FGN, ENO, NUB] for example. However the current output is [FEN, GNU, NOB] [SOY, SOY, SOY] or [FEN, GNU, NOB] [].
The Test Class
public class Test_WordPuzzleGenerator {
public static void main(String[] args) throws FileNotFoundException {
System.out.println("Test 1: size 3");
int size = 3;
Puzzle.WordPuzzleGenerator.generatePuzzle(size);
}
}
WordGenerator:
public class WordPuzzleGenerator {
static ArrayList<String> wordList = new ArrayList<String>();
public static void generatePuzzle(int size) throws FileNotFoundException {
ArrayList<String> puzzleListY = new ArrayList<String>();
ArrayList<String> puzzleListX = new ArrayList<String>();
String randomXWord;
String letterSize = "" + size;
makeLetterWordList(letterSize);
boolean finished = false;
while ( !finished ) {
finished = true;
puzzleListX.clear();
puzzleListY.clear();
for (int i = 0; i < size; i++) {
int randomYWord = randomInteger(wordList.size());
String item = wordList.get(randomYWord);
puzzleListY.add(item);
}
for (int i = 0; i < puzzleListY.size(); i++) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < puzzleListY.size(); j++) {
sb.append(puzzleListY.get(j).charAt(i));
}
randomXWord = sb.toString();
if (!wordList.contains(randomXWord)) {
break;
}
puzzleListX.add(randomXWord);
if (puzzleListX.size() == size){
finished = false;
}
}
}
System.out.print(puzzleListY);
System.out.print(puzzleListX);
}
public static int randomInteger(int size) {
Random rand = new Random();
int randomNum = rand.nextInt(size);
return randomNum;
}
public static void makeLetterWordList(String letterSize) throws FileNotFoundException {
Scanner letterScanner = new Scanner( new File (letterSize + "LetterWords.txt"));
wordList.clear();
while (letterScanner.hasNext()){
wordList.add(letterScanner.next());
}
letterScanner.close();
}
}
I think you are confusing yourself with that finished variable. Replace the while condition with puzzleListX.size() != size and your code should work.
This question already has answers here:
How to read array of integers from the standard input in Java?
(2 answers)
Closed 8 years ago.
So my code looks like this so far:
public class PancakeSort {
public static int flip(int n) {
int temp = 0;
for (int i = 0; i < (n+1) / 2; ++i) {
int[] pancakes = new int[n];
temp = pancakes[i];
pancakes[i] = pancakes[n-i];
pancakes[n-i] = temp;
}
return temp;
}
public static void sort (int[] pancakes) {
for (int i=0; i<pancakes.length; i++){
if (pancakes[i] > pancakes[i+1]){
flip(i+1);
}
}
System.out.println(pancakes);
}
public static void main(String[] args) {
}
}
But how I input a whole array of integers using standard input (StdIn.readLine())? I understand that the code might not be correct and I'm working on figuring that out,and I'm also aware that this question has been asked before in this site, but not specifically using the standard library and that is where I'm stuck.
You can send integer array as input
PancakeSort pancakeSort = new PancakeSort();
pancakeSort.sort(new int[] { 100, 50, 89, 2, 5, 150 });
or Use scanner class as
int arr[] = new int[10];
Scanner sc = new Scanner(System.in);
int i = 0;
while (sc.hasNextInt()) {
arr[i] = sc.nextInt();
i = i + 1;
}
PancakeSort pancakeSort = new PancakeSort();
pancakeSort.sort(arr);
But in last case you must not increased the size of array.Otherwise it will give arrayIndexOutOfBoundException
I believe you may be referencing StdIn such as a class like this one?
http://introcs.cs.princeton.edu/java/stdlib/StdIn.java.html
If so, then to get an int from the console you just call StdIn.readInt. An example of how you could approach this is:
public static void main(String[] args)
{
System.out.println("Enter number of pancakes, or enter 0 to quit");
int[] pancakeArray = new int[0];
while (true)
{
try
{
int entry = StdIn.readInt();
if (entry == 0)
{
break;
}
int[] expandedArray = new int[pancakeArray.length + 1];
System.arraycopy(pancakeArray, 0, expandedArray, 0, pancakeArray.length);
expandedArray[pancakeArray.length] = entry;
pancakeArray = expandedArray;
}
catch (Exception e)
{
System.out.println("Invalid entry detected, closing input");
break;
}
}
System.out.println("Pancake array length: " + pancakeArray.length);
sort(pancakeArray);
System.out.println("Final pancake array in order:");
for (int entry : pancakeArray)
{
System.out.println("Pancake value: " + entry);
}
}
This would read int after int until they entered 0 or an invalid value, then it would call your sort routine from there. There are issues in your sort routine but you said you wanted to look at that, so I will let you figure that part out.
For example if the input is "name" and the minGram is 1 and maxGramSize is 2 output will consist of n,a,m,e,na,am,me. If the minGram=2, maxGram=4 inputWord=name, output = na,am,me,nam,ame,name.
Function signature can be something like this:
public List<String> generateNGrams(String input, int minGramSize, int maxGramSize)
Initially I tried doing it with for loops, but I was finding it hard to follow the indices. Then I tried solving it using recursion with pen and paper but I'm still struggling with it. Can someone help me with this?
One solution:
private static void addNgrams(final int size, final String input,
final List<String> list)
{
final int maxStartIndex = input.length() - size;
for (int i = 0; i < maxStartIndex; i++)
list.add(input.stubString(i, i + size));
}
public List<String> generateNGrams(final String input, final int minSize,
final int maxSize)
{
final List<String> ret = new ArrayList<>();
for (int size = minSize; size <= maxSize; size++)
addNgrams(size, input, ret);
return ret;
}
Note: lacks basic error checkings (for instance, maxSize greater than the size of input; minSize greater than maxSize; others); left as an exercise.
Here is a program that recursively generates nGrams: This code also handles the tail grams.
import java.util.ArrayList;
public class NGrams {
ArrayList<String> nGrams = new ArrayList<String>();
public void generateNGrams(String str, int n) {
if (str.length() == n ) {
int counter = 0;
while (counter < n) {
nGrams.add(str.substring(counter));
counter++;
}
return;
}
int counter = 0;
String gram = "";
while (counter < n) {
gram += str.charAt(counter);
counter++;
}
nGrams.add(gram);
generateNGrams(str.substring(1), n);
}
public void printNGrams() {
for (String str : nGrams) {
System.out.println(str);
}
}
public static void main(String[] args) {
NGrams ng = new NGrams();
ng.generateNGrams("hello world", 3);
ng.printNGrams();
}
}
Output:
hel
ell
llo
lo
o w
wo
wor
orl
rld
ld
d