How do I show the values in both dimensional arrays? - java

I want to insert Coordinate x and y into both dimensional arrays and print it out. For the example given to the given code when it asks for input it doesn't do it once but twice then accepts the value. I don't if the values are actually getting stored in each array or just one. Is it possible to show output independently of the matrix? I aprecciate any help or corrections! Bless you.
Here's the code:
Code
import java.util.Scanner;
public class MummyMadness {
public static void main(String []args){
int [][] desert = new int [1][1];
int x =0;
int y =0;
int mummies[] = new int [1];
int Mlimit = 100000;
coordinates(desert,mummies,x,y);
}
public static int[] inputmummy(int mummies[], int Mlimit){
int i;
Scanner input = new Scanner(System.in);
System.out.println("How many mummies you want?");
System.out.println("Note that the limit of mummies is 100k");
i = input.nextInt();
if(mummies[i] > Mlimit)
{
System.out.println("You exceeded from the mummies!");
}
return mummies;
}
public static int[][] coordinates(int desert[][],int mummies[], int x, int y){
//Idea use length of mummies for coordinates but if you take out desert i doesnt work
System.out.println("Enter mummy coordinates");
for(int i = 0; i < desert.length; i++){
System.out.println("Enter x:");
Scanner input = new Scanner(System.in);
if(input.nextInt() > desert.length)
{
System.out.println("Error x exceeded desert length");
break;
}
desert[i][0] = input.nextInt();
System.out.println("Mummy location x: " + desert[i][0]);
for(int j = 0; j < mummies.length; j++){
System.out.println("Enter y:");
Scanner input2 = new Scanner(System.in);
if(input.nextInt() > desert[0].length)
{
System.out.println("Error y exceeded desert length");
break;
}
desert[0][j] = input2.nextInt();
System.out.println("Mummy location y: " + desert[0][j]);
System.out.println(desert[i][j])
}
}
return desert;
}
}

You are using input.nextInt twice() - once for checking and once for actually inserting into array. Everytime you call this function, it expects an input. Hence its asking for input twice.
Do this instead:
int tmp = input.nextInt();
if(tmp > desert.length)
{
System.out.println("Error x exceeded desert length");
break;
}
desert[i][0] = tmp;

Related

Printing out the array position from a number input by a user

Question:
I need to create an array that holds 1000 integers ranging from 1-100. I then need to ask the user for an input and find out if the number the user has input is present in the array. If its not, then I have to output the message that it is not in the array.
I populated the array with random numbers, just need to find out how to search for the number in the array. I tried using a while loop to condition the for loop, but cant because the random generator and searcher would be in the same loop. Is there a way to linearly search for the number?
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
int[] numbers = new int[1000];
System.out.println("Please enter a number: ");
int n = Integer.parseInt(reader.nextLine());
for(int i = 0; i < 1000; i = i + 1)
{
numbers[i] = (int)(Math.random()*100);
}
}
}
Try this
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int[] numbers = new int[1000];
boolean found = false;
System.out.println("Please enter a number: ");
int n = Integer.parseInt(reader.nextLine());
for(int i = 0; i < 1000; i = i + 1)
{
numbers[i] = (int)(Math.random()*100);
}
for(int i =0; i < 1000; i++){
if(numbers[i] == n){
found = true;
System.out.println(numbers[i] + " Appears first at index " + i);
break;
}
}
if(!found){System.out.println("Number " + n + " is not in the list");}
}

How do I output a TABLE with names and scores with only using Arrays and Methods?

I have been trying to find the answer to this question but to no avail!
Basically I have to write a program where 'x' number of players can enter a guessing game and input their guesses and then get a score.
However, right after they input their guesses, i have to output it in a table form like this "NAME GUESS SCORE"
I do not know how i can do this with a for loop since a for loop println can only print values from playersArray. How can I print another array like guessesArray to the side of it?
I can only use Arrays and Methods to do this.
Below I will show u what i have right now:
import java.util.Scanner;
import java.util.Random;
import java.lang.Math;
public class game
{
static int[] guessesArray;
static int guess;
static String [] playersArray;
static int[] currscoresArray;
static int [] addscoresArray;
static int [] finalscoresArray;
public static void main(String [] args){
System.out.print("Number of players? ");
Scanner kb = new Scanner(System.in);
int numplayers = kb.nextInt();
//Initialize
playersArray = new String[numplayers];
guessesArray = new int [numplayers];
currscoresArray = new int [numplayers];
addscoresArray = new int [numplayers];
finalscoresArray = new int [numplayers];
populateArray(playersArray);
displayMenu();
}
public static void populateArray( String[] x){
Scanner kb = new Scanner(System.in);
for (int i = 0; i<x.length ; i++){
System.out.print("Enter Player "+(i+1)+": ");
x[i]=kb.nextLine();
}
}
public static void displayMenu(){
int choice=0;
Scanner kb = new Scanner(System.in);
String[] args = {};
while(true){
System.out.println("Menu ");
System.out.println("1. Make Guess");
System.out.println("2. List Winner");
System.out.println("0. Exit");
System.out.print("Enter choice: ");
choice = kb.nextInt();
if (choice==0){
System.out.print("Do you want to play a new game? Y/N: ");
String ans = kb.next();
if (ans.equals ("Y") || ans.equals ("y")){
main(args);
}
break;
}
switch (choice){
case 1: makeGuess(); break;
case 2: listWinner(); break;
default: System.out.println("Invalid choice");
}
}
System.out.println("End of program");System.exit(0);
}
public static void makeGuess(){
Scanner kb = new Scanner(System.in);
Random rand = new Random();
int secret = rand.nextInt(10)+1;
for (int i=0; i < guessesArray.length; i++){
System.out.print("Enter your guess "+playersArray[i]+": ");
guessesArray[i]=kb.nextInt();
}
int diff = (int)(Math.abs(guess - secret));
int score=0;
if (diff == 0){
score=score+10;
}else if(diff<=1){
score=score+5;
}else if(diff<=2){
score=score+2;
}
for (int i=0; i< currscoresArray.length; i++){
currscoresArray[i]=score;
}
System.out.println();
System.out.println("Generated number is "+secret);
System.out.println("Current Score Listing");
System.out.println(" Name Guess Score Added Final Score");
System.out.println("1. "+playersArray[0]+" \t "+guessesArray[0]+" \t"+currscoresArray[0]+"");
System.out.println("1. "+playersArray[1]+" \t "+guessesArray[1]+" \t"+currscoresArray[1]+"");
}
public static void listWinner(){
}
}
just reuse a int x variable when printing from each array?
for( int x = 0; x < playersArray.length; x++ ) {
System.out.println( playersArray[ x ] + ” ” + guessArray[ x ] + " " + finalScoresArray[ x ] );
}
you already give an example in your code where you print the 3 values with a single print method. you used a for loop for indexing an element in an array. So combing the 2 techniques shouldn't be too difficult to grasp.
Instead of using an enhanced for loop (e.g. for (String player : playersArray) {}, you can use an indexed one:
for (int i = 0; i < playersArray.length; i++) {
String name = playerArray[i];
double score = scoresArray[i];
}
That being said, you should really make a Player class, that holds all information of a single player, and then have just one array, of that type. That's much nicer, not only because you can use enhanced fors, but because you don't need to make sure the arrays are always synced, and your code becomes way easier to understand.

How can the numbers in array count to odd or even number?

I wrote the code in java but it does not count to odd or even. It only counts in even numbers. If I miss anything?
import java.util.Scanner;
public class OddEven {
//create the check() method here
static void check(int[] x, int n) {
x = new int[100];
Scanner in = new Scanner(System.in);
while (in.hasNextInt()) {
x[n++] = in.nextInt();
}
if (x[n] % 2 == 0) {
System.out.println("You input " + n + " Even value");
} else if (x[n] % 2 == 1) {
System.out.println("You input " + n + " Odd value");
}
while (in.hasNextInt()) ;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//read the data here
System.out.print("Input a list of Integer number : ");
int[] x = new int[100];
int n = 0;
check(x, n);
in.close();
}
}
Check these loops:
This essentially puts all the ints in x.
while(in.hasNextInt()) {
x[n++] = in.nextInt();
}
This just loops until it doesn't have an it.
while(in.hasNextInt());
Which means, the if block is not even in a loop. However, the first while loop post increments n, which means even if you have one number, it will assign:
x[0] = 123;
but then n=1. which means, the if block will check the next field. But by default it is 0, which will display that it is even.
This would make more sense:
x= new int[100];
Scanner in = new Scanner(System.in);
while(in.hasNextInt()) {
x[n] = in.nextInt();
if(x[n]%2==0){
System.out.println("You input "+n+" Even value");
}else if(x[n]%2==1){
System.out.println("You input "+n+" Odd value");
}
n++;
}

Scanner cannot read input

package algo.chapter1.Ex1_1_33;
import java.util.Scanner;
import edu.princeton.cs.introcs.StdIn;
import edu.princeton.cs.introcs.StdOut;
public class MatrixClient
{
static Scanner scan = new Scanner(System.in);
public static void main(String[] args)
{
while(true)
{
switch (getInput())
{
case 1:
//Dot Product
performDotProduct();
break;
case 2:
performMatrixProduct();
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
StdOut.println("Thank You!");
System.exit(0);
break;
default:
StdOut.println("Invalid Choice!!!");
}
}
}
public static int getInput()
{
StdOut.println("******************************");
StdOut.println("1.Dot Product");
StdOut.println("2.Matrix-Matrix product");
StdOut.println("3.Transpose");
StdOut.println("4.Matrix-Vector Product");
StdOut.println("5.Vector-Matrix product");
StdOut.println("6.Exit");
StdOut.println("******************************");
StdOut.print("\nChoose one from the above: ");
return StdIn.readInt();
}
public static void performDotProduct()
{
StdOut.print("Enter elements of vector A: ");
double[] A = readVector();
StdOut.print("Enter elements of vector B: ");
double[] B = readVector();
StdOut.println("The dot product is: " + Matrix.dot(A, B));
}
public static void performMatrixProduct()
{
StdOut.print("Enter the size of matrix A: ");
int size = scan.nextInt();
double[][] A = readMatrix(size);
for (double[] row : A)
{
for (double item : row)
StdOut.print(item + "\t");
StdOut.println();
}
}
public static double[] readVector()
{
String[] input = scan.nextLine().split(" ");
double[] x = new double[input.length];
for (int i = 0; i < input.length; i++)
x[i] = Double.parseDouble(input[i]);
return x;
}
public static double[][] readMatrix(int N)
{
int counter = 0;
double[][] matrix = new double[N][N];
while (counter < N)
{
StdOut.print("Enter elements of row " + (counter + 1) + ": ");
matrix[counter] = readVector();
counter++;
}
return matrix;
}
}
I'm using readVector() method to read a row of doubles and return a double array. When it is used for dot product, input is being read returned fine, but when I use matrix-matrix multiplication option, readVector() doesn't wait for input. It throws NumberFormatExcpetion: empty string.
I don't understand why readVector() behaves differently.
The problem is in this line:
int size = scan.nextInt();
When your code asks to enter the size of the matrix, you enter a number, and then hit enter. The above code, however, only reads the number that you enter. It does not consume the enter (\n character).
After your code consume the matrix size, your code does:
String[] input = scan.nextLine().split(" ");
which consumes the enter (\n character), and then split it by space. This (scan.nextLine()), of course, returns an empty string.
To fix it, instead of using:
int size = scan.nextInt();
use:
int size = scan.nextInt();
scan.nextLine();
In your code change:
int size = scan.nextInt();
To
int size = scan.nextInt();
scan.nextLine();

I cannot return a value from my array

This is assessed work so please don't give a straight answer.
My program is supposed to calculate the users grade: "pass" , "fail" or "pass with compensation". However, it doesn't return the answer. I'm unable to figure out why - can anyone help?
public class MarkCalculator {
static int[] marks = new int[12];
//public static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int weighting;
int coursework;
int exammark;
System.out.println("Please enter course work weighting");
marks[0]= kb.nextInt();
System.out.println("Please enter course work mark");
marks[1]= kb.nextInt();
System.out.println("Please enter exam mark");
marks[2]= kb.nextInt();
MarkCalculator mc = new MarkCalculator();
mc.computeMarks(marks);
}
public String[] computeMarks(int[] marks) {
final int[] WEIGHTING = {55,66,55,44,33,44};
String[] results = new String[WEIGHTING.length];
for (int i = 0; i < marks.length / 2; i++) {
int exam = marks[i];
int cw = marks[i];
int weight = WEIGHTING[i];
int formula = ((cw + weight) + (exam * (100 - weight)) / 100);
if (formula >= 40){
results[i]="PASS";
} else if ((formula < 39) && (formula > 35)){
results[i]="COMPENSATION PASS";
}else{
results[i]="FAIL";
}
}
return results;
}
}
final int[] WEIGHTING = {};
String[] results = new String[WEIGHTING.length];
Here's a problem. WEIGHTING has no initial size.
Also: you don't initialize marks with anything. Try this:
System.out.println("Please enter course work weighting");
marks[0]= kb.nextInt();
System.out.println("Please enter course work mark");
marks[1]= kb.nextInt();
System.out.println("Please enter exam mark");
marks[2]= kb.nextInt();
MarkCalculator mc = new MarkCalculator();
mc.computeMarks(marks);
The problem is WEIGHTING is empty
final int[] WEIGHTING = {}; // empty
String[] results = new String[WEIGHTING.length];
for (int i = 0; i < marks.length / 2; i++) {
int exam = marks[i];
int cw = marks[i];
int weight = WEIGHTING[i]; // You cant access elements from an empty array
Also
MarkCalculator mc = new MarkCalculator();
mc.computeMarks(marks);
here you are passing marks which is empty.
EDIT
Reason why your program wasnt working is because you are not catching the result from computeMarks. You should store it in an array inside main like
String[] result = mc.computeMarks(marks);
for(int k=0;k<result.length;k++)
{
System.out.println(result[k]);
}

Categories