How is using a char array parameter benefits the solution? - java

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.

Related

Error in Exception in thread "main" java.lang.NullPointerException at CourseTest.main(CourseTest.java:11) in Java Arrays

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.

trying to print arrays in java [closed]

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

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);
}

read lines from external file and store elements in array

I am new here so please show some patience. I am trying to read the data from an external file and store the info in 2 arrays.
The file looks like this:
0069 723.50
0085 1500.00
0091 8237.31
I am using 2 scanners to read the input and I think they work ok because when I try to print, the result looks ok.
My first problem is that I am able to read the first numbers on the list using nextInt(), but cannot use nextDouble() for the double ones as I get the "java.util.InputMismatchException" message. For that reason I read it as a String. The part with the other two scanners is supposed to do what the first parts should do, for a different input file, but the problem is the same.
My next and biggest problem, until now, is that am not able to store the values from the two columns in two distinct arrays. I have tried several ways (all commented) but all fail. Please help and thanks.
Here is my code:
import ui.UserInterfaceFactory;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Scanner;
import ui.UIAuxiliaryMethods;
public class Bank {
static final int MAX_NUMBER_OF_ACCOUNTS = 50;
PrintStream out;
Bank(){
UserInterfaceFactory.enableLowResolution(true);
out = new PrintStream(System.out);
}
void readFiles(){
Scanner balanceFile = UIAuxiliaryMethods.askUserForInput().getScanner();
while(balanceFile.hasNextLine()){
String balance_Line = balanceFile.nextLine();
Scanner accountsFile = new Scanner(balance_Line);
int account = accountsFile.nextInt(); //works
out.printf("%04d ",account);
/*int [] accounts_array = new int [MAX_NUMBER_OF_ACCOUNTS]; //does not store the values properly
int account = accountsFile.nextInt();
for(int j=0; j < accounts_array.length; j++){
accounts_array[j] = account;
}*/
/*int [] accounts_array = new int [MAX_NUMBER_OF_ACCOUNTS]; //java.util.InputMismatchException
for(int j=0; j < accounts_array.length; j++){
accounts_array[j] = accountsFile.nextInt();
//out.printf("%04d \n",accounts_array[j]);
}*/
String balance = accountsFile.nextLine(); //problem declaring balance as a double
out.printf("%s\n",balance);
/*String [] balance_array = new String [MAX_NUMBER_OF_ACCOUNTS]; //java.util.NoSuchElementException
for(int j=0; j < balance_array.length; j++){
accountsFile.useDelimiter(" ");
balance_array[j] = accountsFile.next();
//out.printf("%04d \n",accounts_array[j]);
}*/
}
Scanner mutationsFile = UIAuxiliaryMethods.askUserForInput().getScanner();
while(mutationsFile.hasNext()){
String mutation_Line = mutationsFile.nextLine();
Scanner mutatedAccountsFile = new Scanner(mutation_Line);
int mutated_account = mutatedAccountsFile.nextInt();
out.printf("%04d ",mutated_account);
int action = mutatedAccountsFile.nextInt(); //deposit or withdrawal
/*if (action == 1){
}else{
}*/
out.printf(" %d ",action);
/*Double amount = mutatedAccountsFile.nextDouble();
out.printf(" %5.2f ",amount);*/
String amount = mutatedAccountsFile.nextLine();
out.printf("%s\n",amount);
}
}
void start(){
new Bank();readFiles();
}
public static void main(String[] args) {
new Bank().start();
}
}
The InputMismatchException occurs because you try to read a double using the nextInt() function. To solve this issue, you can first read the tokens as Strings using the next() function and convert them appropriately.
while(mutationsFile.hasNext()){
mutation_Line = mutationsFile.next();
if(mutation_Line.indexOf(".") == -1)
//token is int
else
//token is double
}
Since you already know what the contents of the two columns are, you can store the integers and doubles in two lists and then, if you want, get them into an array.
List<Integer> intList = new ArrayList<Integer>();
List<Double> doubleList = new ArrayList<Double>();
Now replace the if statements in the first snippet with this:
if(mutation_Line.indexOf(".") == -1)
intList.add(new Integer(Integer.parseInt(mutation_Line)));
else
doubleList.add(new Double(Double.parseDouble(mutation_Line)));
In the end, you can get them into arrays:
Object[] intArr = intList.toArray(),
doubleArr = doubleList.toArray();
//display the contents:
for(int i=0; i<intArr.length; i++)
out.printf("%04d\t%.2f\n", Integer.parseInt(intArr[i].toString()),
Double.parseDouble(doubleArr[i].toString()));
OUTPUT:
0069 723.50
0085 1500.00
0091 8237.31
First off, you don't need to use 2 scanners. The Scanner object is simply reading your file, one scanner is plenty to accomplish the task of reading a file.
If you're trying to read the integers/doubles from file and are having trouble with nextInt() and nextDouble(), consider a different approach to parsing (e.g. parse the line into a string, split the line into 2 parts based on a space character, then trim both resulting strings and convert to respective integers/doubles).
Now back to the Scanner parsing the two values, remember first that when you use a next() or nextInt(), etc. those methods consume the next respective token. So parsing a line as a string from the file into another Scanner object is redundant and unnecessary in this case.
If you know your max number of accounts, and it's simply 50, then go ahead an allocate that prior to the while loop.
Here's an alternative approach with the code you posted.
public class App {
static int MAX_NUMBER_OF_ACCOUNTS = 50;
static PrintStream out;
static void readFiles() {
Scanner balanceFile = null;
try {
balanceFile = new Scanner(new File("C:\\Users\\Nick\\Desktop\\test.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (balanceFile == null)
return;
int [] accounts_array = new int [MAX_NUMBER_OF_ACCOUNTS];
double [] balance_array = new double [MAX_NUMBER_OF_ACCOUNTS];
int currentIndex = 0;
while (balanceFile.hasNextLine()) {
int account = balanceFile.nextInt();
double balance = balanceFile.nextDouble();
System.out.print("acc = " + account + " ");
System.out.println("bal = " + balance);
//out.printf("%04d ", account);
accounts_array[currentIndex] = account;
//out.printf("%s\n", balance);
balance_array[currentIndex] = balance;
currentIndex++;
}
balanceFile.close();
}
static void start() {
readFiles();
}
public static void main(String[] args) {
start();
}
}
Please note the excessive use of static could also be avoided in the future, but for the sake of the example it spread like the plague.
As you can see in the logic leading up to the while loop, the scanner object is made from a file I copied your example data into a file on my desktop. The arrays are allocated prior to the while loop (note: see #progy_rock and their use of ArrayList's - may help improve your code in the long run). And finally, note the index count to move the position along in the array to which you are inserting your lines to.

Arrays, algorithms and elements

I am trying to make a poker game through java.
The first thing I wanted to do is distribute 5 cards using arrays. I have done the distribution part, but how can I prevent the same cards being distributed twice. In other words, how can I check if an array already contains an element. I want it to be able to detect if the element already exists in an array, and if it does, I want to be able to change just that card that has been given out twice, help would be much appreciated.
My codes down below,
import java.util.Random;
import java.util.Scanner;
import java.util.Arrays;
public class Poker
{
public final static String[] numbers = {"❤","♠","♦","♣"};
public final static String[] sign = {"1","2","3","4","5","6","7","8","10","J","Q","K","A"};
private String[] hand = {"","","","",""};
private boolean found;
private Random random;
public Poker()
{
found = false;
String hand[] = {"","","","",""};
int tokens = 10;
Scanner in = new Scanner(System.in);
random = new Random();
}
public void handOut()
{
for (int i = 0; i < 5; i++)
{
int numberRandom = random.nextInt(numbers.length);
int signRandom = random.nextInt(sign.length);
String pickedNumber = numbers[numberRandom];
String pickedSign = sign[signRandom];
String combinedSigns = pickedSign + pickedNumber;
hand[i] = combinedSigns;
System.out.print(hand[i] + " ");
}
System.out.println("\n");
}
}
Your choice of terminology is ... err ... interesting :-)
The card value is a "face value", not a sign. And whether it's hearts or diamonds or so on, that's its "suit" rather than its number.
But, on to the question. I believe the best way to do this is to construct an entire 52-card deck out of your facevalue and suit arrays and then use a Fisher Yates shuffle to distribute cards.
This is a nifty way to randomly choose elements from an array without duplicates. The beauty is that the items in the array don't actually need to be shuffled up front. Details on how it works can be found here.
If you can use the collections framework as opposed to an array, create a Stack and populate it with all the 52 cards. then call Collections.shuffle() on it.
finally set hand[i]=(deck name).pop()
Once a card is popped from the stack it will be removed from the deck so it can't be dealt again.
What you want to do is break your code into different methods. You should have a method for generating one card, a method for checking whether or not a card is in the hand, and a method to distribute cards to the hand.
public String generateCard() {
int numberRandom = random.nextInt(numbers.length);
int signRandom = random.nextInt(sign.length);
String pickedNumber = numbers[numberRandom];
String pickedSign = sign[signRandom];
return pickedSign + pickedNumber;
}
public static boolean cardIsInHand(String card) {
for(int i = 0; i < 5; i++) {
if(hand[i] != null && hand[i].contains(card)) {
return true;
}
}
return false;
}
public static void handout() {
for (int i = 0; i < 5; i++) {
String card = generateCard();
while(cardIsInHand(card)) {
card = generateCard();
}
hand[i] = card;
}
}

Categories