I'm finishing up a program that shows an array given from a file, then gives you the total, average, then specific totals of certain rows. The problem I'm having is that the Array has suddenly begun looping once terminated.
I'm working this in Eclipse IDE
String fileName = "";
if (args.length == 0) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the file name :");
fileName = sc.nextLine();
} else {
fileName = args[0];
}
File file = new File("C:\\Users\\AlaynaC\\Desktop\\2darray.txt");
try {
Scanner fin = new Scanner(file);
int size = fin.nextInt();
int[][] arr = new int[size][size];
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
arr[i][j] = fin.nextInt();
Scanner sc = new Scanner(file);
// The first line of the file contains the number of rows in the array.
int noOfRows = Integer.parseInt(sc.nextLine());
// initialize all with -1
int array[][] = new int[noOfRows][10];
for (int o = 0; o < noOfRows; o++) {
for (int g = 0; g < array[o].length; g++) {
array[o][g] = -1;
}
}
int index = 0;
while (sc.hasNextLine()) {
String line = sc.nextLine();
// Each record in the file corresponds to a row in the array.
String numbers[] = line.split(" ");
// Now feeding the data into the array.
for (int o = 0; o < numbers.length; o++) {
array[index][o] = Integer.parseInt(numbers[o]);
}
index++;
}
sc.close();
// This allows the data to be printed to the console.
System.out.println("~~Array~~");
for (int o = 0; o < noOfRows; o++) {
for (int g = 0; g < array[o].length; g++) {
if (array[o][g] != -1)
System.out.print(array[o][g] + " ");
}
System.out.println();
}
}
}
System.out.println("Total: " + getTotal(arr));
System.out.println("Average: " + getAverage(arr));
System.out.println("Row Total: " + getRowTotal(arr, 3));
System.out.println("Column Total: " + getColumnTotal(arr, 2));
System.out.println("Highest in Row:" + highestInRow(arr, 2));
System.out.println("Lowest in Row:" + lowestInRow(arr, 2));
} catch (FileNotFoundException e) {
System.out.println(file.getAbsolutePath() + " is not found!");
}
}
I need the array to only display once. As of right now it is displaying multiple times once the file is entered.
Related
When i ask the user to input a number to delete from the array it simply puts out 0 and than asks to try again i want the number to be deleted completely until the array is empty here is the code i have so far:
import java.util.Scanner;
import java.util.Random;
public class DeleteElements
{
public static void main(String[]args)
{
Scanner keyboard = new Scanner(System.in);
int arr[] = new int[20];
int num, found = 0,
arrSize = 10;
String choice;
Random randomGenerator = new Random();
for (int i = 0; i<10; i++)
{
arr[i] = randomGenerator.nextInt(100);
}
for(int i = 0; i<10; i++)
{
System.out.print("" + arr[i] + " ");
}
do
{
System.out.print("Number to Delete: ");
num = Integer.parseInt(keyboard.nextLine());
if(arrSize <=0)
{
System.out.println("The array is now empty");
break;
}
else
{
for (int i = 0; i<10; i++)
{
if(arr[i] == num)
{
found = 1;
}
if (found == 1)
arr[i] = arr[i + 1];
}
if (found == 0)
System.out.println("Number not found,");
else
{
arrSize--;
int i = 0;
for ( i = 0; i <arrSize; i++);
{
System.out.print("" + arr[i] + " ");
}
found = 0;
}
System.out.println(" Try again (y/n) ? ");
choice = keyboard.nextLine();
}
}while (choice.charAt(0) == 'y' || choice.charAt(0) == 'Y');
}
}
i want it to look something like this:
Array: 3, 63, 45
Delete NUmber: "User inputs 45"
Array: 3, 63
Issue is here:
for ( i = 0; i <arrSize; i++);
You have a semicolon after for loop. Remove that and your code works as expected.
This is my task
I have the program, printing out the values in the arrays, that step does not need to be there, that is the last for loop. Instead of that I need add the rows up, value by value using the die class i have, the code is something.getFaceValue();.
Code is Below
import java.util.Scanner;
class ASgn8
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many players? ");
int playerCount = scan.nextInt(); // get number of participant player...
scan.nextLine();
Die[] tempDie = new Die[5]; // temporary purpose
Die[][] finalDie = new Die[5][]; // final array in which all rolled dies stores...
int tempVar = 0;
String [] playerName = new String[playerCount]; // stores player name
int totalRollDie = 0; // keep track number of user hash rolled dies...
for(int i = 0; i < playerCount; i++) // get all player name from command prompt...
{
System.out.print("What is your name: ");
String plyrName = scan.nextLine();
playerName[i] = plyrName;
}
for(int i = 0; i < playerCount; i++)
{
System.out.println(playerName[i] + "'s turn....");
totalRollDie = 0;
Die d = new Die();
System.out.println("Rolled : " + d.roll()) ;
tempDie[totalRollDie] = d;
totalRollDie++;
System.out.println("Want More (Yes/No) ???");
int choice = scan.nextInt();
while(choice == 1)
{
if(totalRollDie < 5)
{
Die dd = new Die();
System.out.println("Rolled : " + dd.roll()) ;
tempDie[totalRollDie] = dd;
totalRollDie++;
System.out.println("Want More (Yes/No) ???");
choice = scan.nextInt();
}
}
finalDie[i] = new Die[totalRollDie];
for(int var = 0 ; var < totalRollDie ; var++)
{
finalDie[i][var] = tempDie[var];
}
}
for(int i = 0 ;i < playerCount ; i++) //prints out the values stored in the array. need to sum them instead.
{
System.out.println(" --------- " + playerName[i] + " ------------ ");
for(Die de : finalDie[i])
{
System.out.println(de);
}
}
tempDie = null;
}
}
Anyone have any tips?
EDIT: Die class
public class Die
{
private final int MAX = 6;
private int faceValue;
public Die()
{
faceValue = 1;
}
public int roll()
{
faceValue = (int)(Math.random() * MAX) + 1;
return faceValue;
}
public void setFaceValue(int value)
{
faceValue = value;
}
public int getFaceValue()
{
return faceValue;
}
public String toString()
{
String result = Integer.toString(faceValue);
return result;
}
}
Append following code into your existance code,
public static void main(String... s)
{
......
int score[][] = new int[playerCount][2];
for(int i = 0 ;i < playerCount ; i++){ // finally print whatever user's roll value with all try...
// System.out.println(" --------- " + playerName[i] + " ------------ ");
int playerTotalScore = 0;
for(Die de : finalDie[i]){
// System.out.println(de);
playerTotalScore += de.getFaceValue();
}
score[i][0] = i;
score[i][1]=playerTotalScore;
}
tempDie = null;
System.out.println("------------- Participant Score Card -------------");
System.out.println("Index PlayerName Score");
for(int i = 0 ; i < score.length ; i++){
System.out.println(score[i][0] + " - " + playerName[score[i][0]] + " - " + score[i][1]);
}
int temp[][] = new int[1][2];
for(int i = 0 ; i< score.length; i++){
for(int j = i+1 ; j<score.length;j++){
if(score[i][1] < score[j][1]){
temp[0][0] = score[i][0];
temp[0][1] = score[i][1];
score[i][0] = score[j][0];
score[i][1] = score[j][1];
score[j][0] = temp[0][0];
score[j][1] = temp[0][1];
}
}
}
System.out.println("--------------------------------------------------------");
System.out.println("-----------------WINNER---------------------");
System.out.println(score[0][0] + " - " + playerName[score[0][0]] + " - " + score[0][1]);
System.out.println("--------------------------------------------------------");
} // end of main method...
If I understand your question well, you could store the value in a variable;
int[] mPlayerScores = new int[playerCount];
String name = "";
for(int i = 0 ;i < playerCount ; i++) //prints out the values stored in the array. need to sum them instead.
{
int playerScoreSum = 0;
name = playerName[i];
System.out.println(" --------- " + name + " ------------ ");
for(Die de : finalDie[i])
{
playerScoreSum += de;
}
// this should store the sums in an array
mPlayerScores[i] = playerScoreSum;
//display the result for each player outside the for-loop to avoid continous printing
System.out.println(playerScoreSum);
}
//finds the highest score
double max = mPlayerScores[0];
for (int j = 1; j< mPlayerScores.length; j++)
{
if (mPlayerScores[j] > max)
{
max = mPlayerScores[j];
}
}
System.out.println(name+" is the winner with " + max+ " score");
Your program should display whether the inputted integer value is found in list, how many of it is in list, and what are their locations in list?
sample
List : 1 3 2 5 7 8 5 6 9 4
Input value to search in List: 9
The value 9 is in List!
There are 4 of it in List.
Located at: list[4], list[5], list[6], list[8]
this is my code
import java.io.*;
public class List{
public static void main(String[] args){
int list[] = new int[10];
int i, num = 0, num1=0;
String input = " ";
BufferedReader in = new BufferedReader(new
InputStreamReader(System.in));
for(i = 0; i < 10; i++){
list[i] = 0;
}
for(i = 0; i < 10; i++){
System.out.print("Input value for list[" + i + "] = ");
try{
input = in.readLine();
num = Integer.parseInt(input);
list[i] = num;
for(i = 0; i < 10; i++){
System.out.println("list[" + i + "] = " +list[i]);
}
for (int b = 0; b < list.length; ++b) {
if (num1 == list[b]) {
returnvalue = b;
break;
}
}
System.out.print("Input value for list");
input = in.readLine();
num1 = Integer.parseInt(input);
}catch(IOException e){}
System.out.println("the position is" + returnvalue);
}
}
}
I think the position that is returning is not accurate can you help me?
This will do what you want... Modify the System.out.println(); part according to your need.
public static void main(String[] args) throws IOException {
int list[] = new int[10];
int i, num = 0, num1 = 0;
int returnvalue = 0;
String input = " ";
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
for (i = 0; i < 10; i++) {
list[i] = 0;
}
for (i = 0; i < 10; i++) {
System.out.print("Input value for list[" + i + "] = ");
input = in.readLine();
num = Integer.parseInt(input);
list[i] = num;
}
for (i = 0; i < 10; i++) {
System.out.println("list[" + i + "] = " + list[i]);
}
System.out.print("Input value for checking in list ");
input = in.readLine();
num1 = Integer.parseInt(input);
boolean flag = false;
int[] arr = new int[10];
int count= 0;
for (int b = 0; b < list.length; ++b) {
if (num1 == list[b]) {
flag = true;
arr[count]=b;
count++;
}
}
if(flag)
{
System.out.println("The value "+num1+" is in List!");
System.out.println("There are "+count+" of it in List");
System.out.print("Located at: ");
for(int j=0; j<count;j++)
{
System.out.print(" List["+arr[j]+"]");
}
}
else {
System.out.print(" Element Not found");
}
}
The Console Part for input output is...
Input value for list[0] = 4
Input value for list[1] = 5
Input value for list[2] = 6
Input value for list[3] = 4
Input value for list[4] = 5
Input value for list[5] = 6
Input value for list[6] = 5
Input value for list[7] = 4
Input value for list[8] = 4
Input value for list[9] = 6
list[0] = 4
list[1] = 5
list[2] = 6
list[3] = 4
list[4] = 5
list[5] = 6
list[6] = 5
list[7] = 4
list[8] = 4
list[9] = 6
Input value for checking in list 4
The value 4 is in List!
There are 4 of it in List.
Located at:List[0] List[3] List[7] List[8]
Fixes in your code
A try block is either with a catch block or with a finally block or both.
Having two same variables in inner and outer loop is not good. In your case the outer loop will iterate just once. I think which is not needed.
There are two nested for loop where the loop control variable is same:
for(i = 0; i < 10; i++){
System.out.print("Input value for list[" + i + "] = ");
...
for(i = 0; i < 10; i++){
System.out.println("list[" + i + "] = " +list[i]);
}
...
So, the outer for loop will never iterate what you are expecting. Use a different loop control variable for the inside for loop.
here is my solution for your problem. no need to use that much of loops. you want to use only one foreach - How does the Java 'for each' loop work? (if you don't need to ask question again and agian). I was unable to test this lot :). But, I hope this will work.
import java.util.*;
class MyList{
public static void main(String arga[]){
int array[] = {1,3,2,5,7,8,5,6,9,4};
Scanner input = new Scanner(System.in);
// recursively ask the question
while(true){
System.out.print("Enter the value to search in list: ");
int value = input.nextInt();
System.out.println();
int i = 0;// to get the array index
int count = 0; // to get how many
String list = "Located at: ";
boolean isTrue = false; // to get entered value is in the list or not
for(int a: array){
if(a == value){
isTrue = true;
list += "list[" + i + "],";
count++;
}
i++;
}
if(isTrue){
//remove the last "," from the string
list = list.substring(0, list.length() - 1);
System.out.println("The value " + value +" is in List!");
System.out.println("There are " + count +" of it in List.");
System.out.println(list);
}else{
System.out.println("this value is not in the list");
}
}
}
}
can anybody help me figure out why my for loops cant print the right answer out.
Its like its skipping the first array number [0]. but if i try to make it print out my Array nr [1] out it works fine.
It must be somthing with my counter ans answer at the top.
package assignment9.pkg1;
import java.util.Scanner;
/**
*
* #author Anders
*/
public class Assignment91 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String studName = "Anders";
int counter = 1;// i think the problem is here
int answer = 1; // same
System.out.println(" welcome to student database, show informations about student" + studName);
Scanner courseScan = new Scanner(System.in);
Scanner gradeScan = new Scanner(System.in);
Scanner answerScan = new Scanner(System.in);
System.out.println(" Enter the name of courses");
String[] courseArray = new String[counter];
int[] gradeArray = new int[counter];
for (int k = 0; k <= counter; k++) {
if (counter < 20) {
while (answer != 0) { // what have i done here with that 0 answer??
System.out.println(" enter name");
courseArray[k] = courseScan.nextLine();
System.out.println(" Enter grade");
gradeArray[k] = gradeScan.nextInt();
System.out.println(" Do you want to add one more course enter 1, if not enter 0");
answer = answerScan.nextInt();
}
} else {
System.out.println("Sorry, there is no more memory");
}
}
int n = gradeArray.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (gradeArray[j - 1] > gradeArray[j]) {
//swap the elements!
temp = gradeArray[j - 1];
gradeArray[j - 1] = gradeArray[j];
gradeArray[j] = temp;
// Swap the course array
String gradeArrayTemp;
gradeArrayTemp = courseArray[j - 1];
courseArray[j - 1] = courseArray[j];
courseArray[j] = gradeArrayTemp;
}
}
}
for (int l = 0; l < courseArray.length; l++) {
System.out.println("grade " + gradeArray[l] + "name " + courseArray[l]); // why does it not print all the array out
}
Scanner request = new Scanner(System.in);
System.out.println(" what do you want to do. Enter 1 to rename a course");
System.out.println(" enter 2 to change a grade ");
int regNumber = request.nextInt();
switch (regNumber) {
case 1: // rename a course
Scanner search = new Scanner(System.in);
System.out.println("Enter the name of the course you want to rename");
String searchCourse = search.nextLine();
for (int i = 0; i < courseArray.length; i++) {
if (searchCourse.equals(courseArray[i])) {
System.out.println("Yes there is a course named " + courseArray[i]);
System.out.println(" to change coursename insert new name");
// here i change the coursename
Scanner newName = new Scanner(System.in);
courseArray[i] = newName.nextLine();
} else {
System.out.println(" no record of this course");
}
System.out.println(" you have chosen to rename course into " + courseArray[i]);
}
}
}
}
In this section of the code:
for (int k = 0; k <= counter; k++) {
if (counter < 20) {
while (answer != 0) { // what have i done here with that 0 answer??
System.out.println(" enter name");
courseArray[k] = courseScan.nextLine();
System.out.println(" Enter grade");
gradeArray[k] = gradeScan.nextInt();
System.out.println(" Do you want to add one more course enter 1, if not enter 0");
answer = answerScan.nextInt();
}
} else {
System.out.println("Sorry, there is no more memory");
}
}
note that you have used k to insert into array. the k do not update because is stuck in the inner while loop There for use another counter.
Also here
String[] courseArray = new String[counter];
you use counter to create the array. Which is 1. You are creating one eliment array.
You code will work like this:
int k = 0;
if (counter < 20) {
while (answer != 0) { // what have i done here with that 0 answer??
System.out.println(" enter name");
courseArray[k] = courseScan.nextLine();
System.out.println(" Enter grade");
gradeArray[k] = gradeScan.nextInt();
System.out.println(" Do you want to add one more course enter 1, if not enter 0");
answer = answerScan.nextInt();
k++;
}
} else {
System.out.println("Sorry, there is no more memory");
}
And
for (int i = 0; i < courseArray.length; i++) {
if(courseArray[i] != null)
System.out.println("grade " + gradeArray[i] + "name " + courseArray[i]); // why does it not print all the array out
}
I have assumed that you take only 20 records depending on the loop. So i initiated arrays
String[] courseArray = new String[20];
int[] gradeArray = new int[20];
my code (reads a text file, uses a class I built to sort through the data, and then outputs onto console), is not printing anything! Can somebody please tell me where my little mistake is! I know the VERY end is not finished yet. Please help!!!!!!!!
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class Project02 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<Product> products = new ArrayList<Product>();
// Enter file name
System.out.print("Enter database file name: ");
String fileName = in.nextLine();
try {
File file = new File(fileName);
Scanner inputFile = new Scanner(file);
System.out.println();
while (inputFile.hasNext()) {
Product p = new Product();
String title = inputFile.nextLine();
String code = inputFile.nextLine();
Integer quantity = inputFile.nextInt();
Double price = inputFile.nextDouble();
inputFile.nextLine();
String type = inputFile.nextLine();
Integer userReview = inputFile.nextInt();
// read in title
p.setName(title);
// read in iCode
p.setInventoryCode(code);
// read in quantity
p.setQuantity(quantity);
// read in price
p.setPrice(price);
// read in type
p.setType(type);
// read in user reviews
while (!userReview.equals(-1)) {
p.addUserRating(userReview);
userReview = inputFile.nextInt();
}
if (inputFile.hasNext()) {
inputFile.nextLine();
}
}
inputFile.close();
} catch (IOException e) {
System.out.println("There was an error reading from " + fileName);
}
}
private static String highRating(ArrayList<Product> p) {
int highestR = 0;
int indexOfHighestR = 0;
for (int i = 0; i < p.size(); i++) {
int rating = p.get(i).getAvgUserRating();
if (p.get(i).getAvgUserRating() > highestR) {
highestR = p.get(i).getAvgUserRating();
indexOfHighestR = i;
}
}
int zero = 0;
String Star = " ";
while (highestR > zero) {
Star = Star + "*";
zero--;
}
String highestRateTitle = p.get(indexOfHighestR).getName() + " ("
+ Star + ")";
return highestRateTitle;
}
private static String lowestRating(ArrayList<Product> p) {
int lowestR = 0;
int indexOfLowestR = 0;
for (int i = 0; i < p.size(); i++) {
int rating = p.get(i).getAvgUserRating();
if (p.get(i).getAvgUserRating() < lowestR) {
lowestR = p.get(i).getAvgUserRating();
indexOfLowestR = i;
}
}
int zero = 0;
String Star = " ";
while (lowestR > zero) {
Star = Star + "*";
zero--;
}
String highestRateTitle = p.get(indexOfLowestR).getName() + " ("
+ Star + ")";
return highestRateTitle;
}
private static double maxDollar(ArrayList<Product> p) {
double largestP = 0;
int indexOfLargestP = 0;
for (int i = 0; i < p.size(); i++) {
double price = p.get(i).getPrice();
if (p.get(i).getPrice() > largestP) {
largestP = p.get(i).getPrice();
indexOfLargestP = i;
}
}
return largestP;
}
private static int minDollar(ArrayList<Product> p) {
double smallestP = p.get(0).getPrice();
int indexOfSmallestP = 0;
for (int i = 0; i < p.size(); i++) {
if (p.get(i).getPrice() < smallestP) {
smallestP = p.get(i).getPrice();
indexOfSmallestP = i;
}
}
return indexOfSmallestP;
}
private static void inventoryList(ArrayList<Product> p) {
int count =
System.out.println("Product Summary Report: ");
System.out
.println("------------------------------------------------------------");
for (int i = 0; i < count; i++) {
System.out.println("Title: " + p.get(i).getName());
System.out.println("I Code: " + p.get(i).getInventoryCode());
System.out.println("Product Type: " + p.get(i).getType());
System.out.println("Rating: " + p.get(i).getAvgUserRating());
System.out.println("# Rat.: " + p.get(i).getUserRatingCount());
System.out.println("Quantity: " + p.get(i).getQuantity());
System.out.println("Price: " + p.get(i).getPrice());
System.out.println();
}
System.out
.println("-----------------------------------------------------------------");
// System.out.println("Total products in database: " + count);
System.out.println("Highest total dollar item: "
+ p.get(maxDollar(p)) + " ($"+ p.(maxDollar(p)) + ")");
System.out.println("Smallest quantity item: "
+ p.get(minQuantity(quantities)) + " ("
+ types.get(minQuantity(quantities)) + ")");
System.out.println("Lowest total dollar item: "
+ titles.get(minDollar(prices)) + " ($"
+ prices.get(minDollar(prices)) + ")");
System.out
.println("-----------------------------------------------------------------");
}
First...
After you've create an instance of Product, p, you will need to add it to the products list, otherwise you will lose it's reference and won't be able to use it again...
while (inputFile.hasNext()) {
Product p = new Product();
//...
products.add(p);
if (inputFile.hasNext()) {
inputFile.nextLine();
}
}
Second...
You will need to pass the products List to something that want's to use/display the information, for example inventoryList...
But wait, that's not working?
If we take a closer look at the the inventoryList method...
int count = 0;
//...
for (int i = 0; i < count; i++) {
We can see that count is always 0, so it will never print anything! You should be using p.size() instead, which is the actually length of the products List
//...
for (int i = 0; i < p.size(); i++) {