I don't think that my array is storing and data - java

I am new to java and I am taking a college course right now. I was just curious what I am missing to give myself an output because right now the console is blank.
public static void main(String[] args) throws IOException {
double avgScore;
int highestScore, count = 0;
String highScoringStudent;
String names[] = null;
int scores[] = null;
File myFile = new File("Student_Data.txt");
Scanner inFile = new Scanner(myFile);
inFile.nextLine();
while(inFile.hasNext()) {
for(int i = 0; i > 0; i++) {
names[i] = inFile.next();
scores[i] = inFile.nextInt();
count++;
}
}
System.out.print("Name Score");
System.out.print(names[count] + " " + scores[count]);
}

First of all, I really wouldn't suggest to place a for inside a while loop, especially in this case (because it doesn't work). Here are the problems:
1) Your for loop starts with i = 0, and finishes right away, because !(i > 0) (i is not > 0) - so you are right, no data will be stored in the array!
2) Inside your for loop, you are reading a string, then an int one by one. After you have read them, you should move to the next string and integer to store in the next position of names and score.
3) You are not increasing i: so (if the for was working), you would just keep assigning different values to the array, at the same position (basically resetting the value of a variable every time).
This would be the best code that would work for your case:
int i = 0;
while(inFile.hasNext()) {
names[i] = inFile.next();
scores[i] = inFile.nextInt();
count++;
i++;
}
Hope this helped! :)

Related

NullPointerException in for loop

In the code below I try to get the grade of all my subjects. I get the input via a for loop. But I'm supposed to store the grade ("C" for example) in the grade array but I get a NullPointerException. I don't understand what's wrong with my code since I thought it was good to go.
Also, ignore the names of the subjects since they are in Swedish.
public class Defan{
Scanner sc = new Scanner(System.in);
String grade[];
String gradeName[] = {"Svenska1", "Svenska2", "Svenska3", "Engelska5", "Engelska 6",
"Mattematik 1c", "Mattematik 2c", "Mattematik 3c", "Mattematik 4", "Idrott", "Samhälle", "Religion",
"Historia", "Biologi1", "Biologi2", "Fysik1", "Fysik2", "Kemi1", "Kemi2", "Franska3", "Franska4", "Körsång1", "Körsång2"
, "Gymnasiearbete"};
public void getInput(){
for(int i = 0; i <= gradeName.length; i++){
System.out.println("Enter grade for " + gradeName[i] + ": ");
grade[i] = sc.nextLine();
}
}
It is very obvious, you have to allocate grade array first!
In your constructor:
final int SIZE = 1024;
grade = new String[SIZE];
Actually i prefer to use an ArrayList instead of array in your case.
You are trying to use grade[] array before initializing it. Try
String grade[] = new String[gradeName.length] <br>
And in in your for loop for(int i = 0; i <= gradeName.length; i++)
In condition use only '<' instead of '<=' like this
for(int i = 0; i < gradeName.length; i++)
because 0 is the first index and size-1 is last index.

How do I get my value to print every time the loop increments in Java (For Loop)

I need to create a code that prints a pyramid like structure, given the user integer input which will be printed last. (I have attached an image of a final product below). I am new to programming, have been enjoying it, but am stuck in this problem.
My code can currently produce the user input 4 times. So I feel like I am close, just a little bit of tweaking will get the job done
I need my code to print out every single time that the loop increments instead of just displaying the user input a certain amount of times. I converted the integer to a string so that I can show the value x amount of times, but I feel that this is what is throwing me off. If I can somehow get the string to display the values at every incrementation then I will be golden. PLEASE HELP! Below is my code
import java.util.Scanner; //import scanner
public class NumberStack { // class
static Scanner myScanner; //declare scanner
public static void main(String[] args){ //add main method
myScanner= new Scanner (System.in); //scanner input declaration
int input= 0;
while (true) {
System.out.print("Enter an integer between 0 and 9 inclusive: ");
if (!myScanner.hasNextInt()) {
System.out.println("You have not entered an integer");
}
input= myScanner.nextInt();
if ( (input>=0) && (input<=9) ) {
String smln= Integer.toString(input);
String out="";
for (int p=0; p<input; p++) {
for (int j=0; j<input; j++) {
for (int i=0; i<((input*2)-1);i++) {
out += smln;
}
System.out.println(""+out);
out="";
smln= Integer.toString(input);
}
}
} //end of if statement
else {
System.out.println("You have not entered an integer within range");
}
} //end of while loop
} //end of main method
} //end of class
when you are facing problems like this one, you should try to look for a pattern...check this out
int input = 4;
for(int i = 1; i <= input; i++)
{
int times = i;
int length = 2 * i - 1;
String str = "";
for(int j = 0; j < length; j++)
{
str += i;
}
for(int k = 0; k < times; k++)
{
System.out.println(str);
}
}
Since your method is currently printing the data fro a particular number properly eg for input 4 it is printing
4444
4444
4444
4444
I would suggest that extract ur code for display into a separate function. And call that function using the number from a loop.
for(int i=1; i<=num;i++)
function_f1(i);
This should do the trick for you and since you are starting off with coding , it will also give you ideas on using methods.

Two-Dimensional Array of contacts (Java)

I'm trying to make a basic program that allows the use to input and remove up to 10 contacts (a [10][4] array supposed to be filled with First Name, Last Name, Phone #, and age). However when I try to input the 5th contact eclipse gives me an error message. I'd like to know why I'm receiving an error message. (I assume it's something to do with the columns since it's whenever i'm inputting something >4, but i'm not sure what exactly.)
import java.util.Scanner;
public class Lab2 {
public static void main(String[] args){
new Lab2 ();
}
// This will act as our program switchboard
public Lab2 (){
Scanner input = new Scanner(System.in);
String[][] personalInfo = new String[10][4];
System.out.println("Welcome to the contacts database.");
System.out.println("Please select a number from the options below");
System.out.println("");
while(true){
// Give the user a list of their options
System.out.println("1: Add a new contact.");
System.out.println("2: Remove an existing contact.");
System.out.println("0: Exit the database.");
// Get the user input
int userChoice = input.nextInt();
switch(userChoice){
case 1:
addContact(personalInfo);
break;
case 2:
removeContact(personalInfo);
break;
case 0:
System.out.println("Thank you for using the contact database.");
System.exit(0);
}
}
}
private void addContact(String personalInfo[][])
{
Scanner input = new Scanner(System.in);
System.out.println();
System.out.println( " Hello user, please enter your contact info. (I.E. First and Last Names, Phone #, and Age. Max 10 Contacts)");
String addedContact = input.nextLine();
int j;
for(int i = 0; i < personalInfo.length; i++)
{
for(j = 0; j < personalInfo.length; j++){
if(personalInfo[i][j] == null)
{
personalInfo[i][j] = addedContact;
break;
}
}
}
}
private void removeContact(String personalInfo[][]) {
Scanner input = new Scanner(System.in);
System.out.print( " Please enter an existing contact that you would like to remove. ");
String deleteContact = input.nextLine();
int i , j;
for(i = 0; i < personalInfo.length; i++)
{
for(j = 0; j < personalInfo.length; j++){
if(personalInfo[i][j].equals(deleteContact))
{
personalInfo[i][j] = null;
break;
}
}
}
}
}
Try like this for(j = 0; j < personalInfo[i].length; j++){
First things first:
String[][] personalInfo = new String[10][4];
This statement creates a 2dimensional array of Strings, thus creating an array that is capable of holding an array that is capable of holding strings. (in this case 10 arrays that keep 4 strings each)
Now the error:
String addedContact = input.nextLine();
This line puts the entire line you added in a single string.
Now the loops:
1. The outer loop loops correctly through the 10 arrays of strings.
2. The inner loop does not loop through the '2nd dimension', that is the actual array which will hold your contact. This loop should be as #Kannan Thangadurai described:
for(j = 0; j < personalInfo[i].length; j++){
(add relevant code here)
}
The last error you made is more of a bug, and is in the way you read out the user input. You actually only ever put a string in the first array and so your four contacts that you saved will all be under personalinfo[1] then you try to add another contact in the fifth place of the array that does not exist, thus raising your error.
You're working with jagged array (or array of arrays)
String[][] personalInfo = new String[10][4];
so in order to itterate it you should use different lengths for dimensions (in general case the
required length is personalInfo[i].length):
for (int i = 0; i < personalInfo.length; ++i) // <- outer array
for (int j = 0; j < personalInfo[i].length; ++j) // <- inner length depends on i
if (personalInfo[i][j] == null) {
personalInfo[i][j] = addedContact;
break;
}

Why won't my program continue on once I enter as the itemName?

I can't figure out why my program won't continue past the while loop once I enter the string "end" as one of the items. I tried putting println statements after the while loop and they didn't print after I typed "end". I also tried putting a print statement at the end of the while loop and it did not print once I typed "end", so it isn't running the while loop after I type "end", but it also isn't running anything after it. Any ideas? Here's the code:
package a1;
import java.util.Scanner;
public class A1Adept {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
process(s);
}
public static void process(Scanner s) {
int[] numbers = new int[10];
double[] cost = new double[10];
String itemName = "";
int categoryNumb;
int quantities;
double costs;
System.out.println("Please enter the names of the items, their category, their quantity, and their cost.");
while(!itemName.equals("end")){
itemName = s.next();
categoryNumb = s.nextInt();
quantities = s.nextInt();
costs = s.nextDouble();
numbers[categoryNumb] += quantities;
cost[categoryNumb] += (costs*quantities);
}
System.out.println("win");
int qMax = 0;
int qMin = 0;
int cLarge = 0;
int cLeast = 0;
int max = 0;
int min = 100;
double large = 0;
double least = 100;
for (int i = 0; i < 10; i++){
if (numbers[i] >= max)
{
max = numbers[i];
qMax = i;
}
if (numbers[i] <= min){
min = numbers[i];
qMin = i;
}
if (cost[i] >= large){
large = cost[i];
cLarge = i;
}
if (cost[i] <= least){
least = cost[i];
cLeast = i;
}
}
System.out.println("Category with the most items:"+qMax);
System.out.println("Category with the least items:"+qMin);
System.out.println("Category with the largest cost:"+cLarge);
System.out.println("Category with the least cost:"+cLeast);
}
}
It will stop if you write "end" followed by an int, another int and a double.
This is because you are first checking for "end", then asking for the 4 inputs.
The while(condition) is evaluated at the beginning of every loop.
So your program goes like this :
Check if itemName equals "end"
Ask itemName
Ask categoryNumb
Ask quantities
Ask costs
Do your stuff
Go back to 1
If you want to exit as soon as the user types "end" change it to :
while (true) { // Creates an "endless" loop, will we exit from it later
itemName = s.next();
if (itemName.equals("end")) break; // If the user typed "end" exit the loop
// Go on with the rest of the loop

java program read and print to text file using Scanner

I am trying to read a text file, and then display the output in another file.
I can only read using Scanner.
input.txt
3005045 7
3245436 0
7543536 3
8684383 -1
output.txt should be like
ID Number of Bags Total Cost
** ************** **********
customer pays 20.50 per bag if the bag is 4 or less.
and pays 15.50 per bag if the bag greater than 4.
but if it's 0 or negative number this message should appeared "Error : Wrong Number of Bags"
I did this program, but it works only once(reads one line only)
import java.util.*;
import java.io.*;
import java.io.IOException;
public class Bags {
public static void main(String []args) throws IOException {
FileInputStream fileinput = new FileInputStream("input.txt");
FileOutputStream fileoutput = new FileOutputStream("output.txt");
Scanner infile = new Scanner(fileinput);
PrintWriter pw = new PrintWriter(fileoutput);
double total = 0, line = 0;
int bags = 0, ID = 0, count = 0;
pw.println("ID\t\tNumber of Bags\t\t\tTotal Cost");
for(int i = bags; i >= 0; i++, count++){
ID = infile.nextInt();
i = infile.nextInt();
if (i <= 0){
pw.println(ID + "\tError: Wrong Number of Bags\t\t\t");
break;
}
else if (i <= 4){
total = (80.50)*i;
pw.printf("%d\t\t%d\t\t\t\t%.2f", ID, i, total);
break;
}
else {
total = ((80.50)*4)+((75.50)*(i-4));
pw.printf("%d\t\t%d\t\t\t\t%.2f", ID, i, total);
break;
}
}
infile.close();
pw.close();
}
}
You don't need that for loop over there. Also, you want to read line by line. Here is quick fix of your code:
public class Bags {
public static void main(String[] args) throws IOException {
FileInputStream fileinput = new FileInputStream("input.txt");
FileOutputStream fileoutput = new FileOutputStream("output.txt");
Scanner infile = new Scanner(fileinput);
PrintWriter pw = new PrintWriter(fileoutput);
double total = 0, line = 0;
int bags = 0, ID = 0, count = 0;
pw.println("ID\t\tNumber of Bags\t\t\tTotal Cost");
while(infile.hasNext()){
ID = infile.nextInt();
int i = infile.nextInt();
if (i <= 0) {
pw.println(ID + "\n\t\tError: Wrong Number of Bags\t\t\t");
} else if (i <= 4) {
total = (80.50) * i;
pw.printf("%d\t\t%d\t\t\t\t%.2f", ID, i, total);
} else {
total = ((80.50) * 4) + ((75.50) * (i - 4));
pw.printf("%d\t\t%d\t\t\t\t%.2f", ID, i, total);
}
}
infile.close();
pw.close();
}
}
Output.txt
ID Number of Bags Total Cost
3005045 7 548.503245436
Error: Wrong Number of Bags
7543536 3 241.508684383
Error: Wrong Number of Bags
You should not use i to save "number of bags". See the line i = infile.nextInt();. Use another variable, then you should be fine. Also, you should keep reading until end of file, so you probably wouldn't be able to write a for (int i = 0; i < n; i++)-style of loop.
There is no surprise that loop can iterates only one time. In each case you have break.
Also in this case you shouldn't be using for loop, and especially not the way you are using it now. Just take a look at it, your loop would end only when this condition i >= 0 would be false, which means i would have to be negative, but even when i would become -1 like last number from your input it would still be incremented at the end of iteration thanks to i++ so you would end up with 0 >= 0 condition which is true, so loop would try to iterate again)
Instead use
while(scanner.hasNextInt())
This way you will make sure that you will read int from file only when there will be next one to read. Just use your predefined bugs variable instead of i.
Another thing is that you are not including line separators in your printf formats. Add %n at the end of each one of them, and don't use \t but specify space you want each number to hold like
pw.printf("%d %9d %40.2f%n",...);

Categories

Resources