Currently working on example from a book loop chapter. Basically, there are 4 car sellers and each should have input how many cars they sold. Below inputs, their names should be printed out and in same line number of cars they sold(from input), but not in numbers, using X or star *. x or star represents that number input.
Here is my code so far. I am stuck on printing that X or star next to a name. It prints out next to wrong name. Any way using loops only without array?
import java.io.*;
public class BarGraphCarSold {
public static void main(String[] args)throws IOException {
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter no of cars Bob sold >> ");
int bobSold = Integer.parseInt(buf.readLine());
System.out.print("Enter no of cars Pam sold >> ");
int pamSold = Integer.parseInt(buf.readLine());
System.out.print("Enter no of cars John sold >> ");
int johnSold = Integer.parseInt(buf.readLine());
System.out.print("Enter no of cars Kim sold >> ");
int kimSold = Integer.parseInt(buf.readLine());
System.out.println();
System.out.println("Car Sales for Month");
System.out.print("Bob \n");
System.out.print("Pam \n");
System.out.print("John \n");
System.out.print("Kim ");
for(int i = 1; i<=bobSold;i++){
System.out.print("X");
}
}
}
OUTPUT
Enter no of cars Bob sold >> 5
Enter no of cars Pam sold >> 7
Enter no of cars John sold >> 4
Enter no of cars Kim sold >> 6
Car Sales for Month
Bob
Pam
John
Kim XXXXX
You are close.
try something like this.
System.out.print("Bob ");
for(int i = 0; i < bobSold; i++){
System.out.print("X");
}
System.out.print("\n");
You are printing out each of the names then have newline (\n) then you try to print the X's. So you will need to print their name then the X's then the new line. You will need a loop like that for each of the names you want to print out with their X's.
There are many different ways to do this. You can have a String with their name then loop through and add the X's to the string then print it all out at one time.
String dealer = "Bob ";
for(int i = 0; i < bobSold; i++){
dealer += "X";
}
dealer += "\n";
System.out.print(dealer);
With Arrays
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
String[] dealers = {"Bob","Pam","John","Kim"};
int[] sales = new int[4];
try {
for(int i=0; i < dealers.length; i++){
System.out.print("Enter number of cars "+dealers[i]+" sold: ");
sales[i] = Integer.parseInt(buf.readLine());
}
}catch(IOException e){
System.err.println("Error Reading input");
System.err.println(e.getMessage());
}
System.out.println();
System.out.println("Car Sales for Month");
for(int i = 0; i < dealers.length; i++) {
System.out.print(dealers[i]+" ");
for(int j = 0; j < sales[i]; j++) {
if(j == (sales[i]-1)) {
System.out.println("X");
}else {
System.out.print("X");
}
}
}
}
}
Have fun. Code On.
You need to print the X's for each person.
System.out.print("Bob - ");
for(int i = 1; i<=bobSold;i++){
System.out.print("X");
}
System.out.print("\nPam - ");
for(int i = 1; i<=pamSold;i++){
System.out.print("X");
}
System.out.print("\nSame - ");
for(int i = 1; i<=samSold;i++){
System.out.print("X");
}
System.out.print("\nKim - ");
for(int i = 1; i<=kimSold;i++){
System.out.print("X");
}
Related
So I have to write a program that mimics Megabucks lottery game.
It should either let the user enter 6 numbers OR automatically pick 6 numbers and 1 bonus number. The troubling part is that I have to design it in a way that it will produce 104 drawings(2 drawings a week for 52 weeks). I can't seem to write the code in a way that the 104 drawings are all randomized.
Here's the code I have for drawing the 6 winning numbers and 1 bonus number:
import java.util.*;
public class oops
{
public static void main(String[] args)
{
Random randomGenerator = new Random();
int bonus = randomGenerator.nextInt(42)+1;
List <Integer> winningNumbers = new ArrayList<Integer>(6);
for(int i=0; i < 6; i++)
{
winningNumbers.add(randomGenerator.nextInt(42)+1);
}
System.out.println();
System.out.println("------------------------------------------------------------");
System.out.println(" Winning numbers: "+ Arrays.toString(winningNumbers.toArray()) +" Bonus Number:" + "[" + bonus + "]");
System.out.println("------------------------------------------------------------");
}
}
And the output for that part is:
As for my code for the rest of the program:
public void getPlayNum()
{
Scanner scan = new Scanner(System.in);
System.out.println(" Enter 1 for manual picking or 2 for automatic: ");
int input = scan.nextInt();
List <Integer> playNumbers = new ArrayList<Integer>();
if(input == 1) //let user pick out their own play numbers
{
for(int i =0; i< 6; i++)
{
System.out.println("Enter number 1 and 42 (no duplicates): ");
int userNum = scan.nextInt();
if(playNumbers.contains(userNum))
{
System.out.println();
System.out.println("*** DUPLICATE FOUND! Please enter a non-repeating digit between 1 and 42 ***");
i--;
System.out.println();
}else if (userNum > 42 || userNum < 1)
{
System.out.println();
System.out.println("*** OUT OF RANGE! Please enter a non-repeating digit between 1 and 42 ***");
i--;
System.out.println();
}else{
playNumbers.add(userNum);
System.out.println("Here are your numbers: ");
System.out.println(Arrays.toString(playNumbers.toArray()));
}
}
}else{
Random randomGenerator = new Random();
for (int index = 0; index < 6; index++)
{
playNumbers.add(randomGenerator.nextInt(42));
}
System.out.println();
System.out.println("Here are the numbers randomly generated for you: ");
System.out.println("------------------------");
System.out.println(Arrays.toString(playNumbers.toArray()));
System.out.println("------------------------");
System.out.println();
}
}
Nothing is properly formatted but I need to fix the important parts first. Thanks for any tips at all!
It is as easy as #Gendarme mentioned:
for(int draw = 0; draw < 104; draw++) {
int bonus = randomGenerator.nextInt(42)+1;
List <Integer> winningNumbers = new ArrayList<Integer>(6);
for(int i=0; i < 6; i++)
{
winningNumbers.add(randomGenerator.nextInt(42)+1);
}
System.out.println();
System.out.println("------------------------------------------------------------");
System.out.println(" Winning numbers: "+ Arrays.toString(winningNumbers.toArray()) +" Bonus Number:" + "[" + bonus + "]");
System.out.println("------------------------------------------------------------");
}
I am sort of new to programming and I am working on a school assignments on arrays
I am suppose to write a program that stores statistics using arrays.
import java.io.*;
public class HockeyLeague {
static final int Rows = 7;
static final int Cols = 8;
static double HockeyChart [][] = new double[Rows][Cols];
static HockeyLeague HL = new HockeyLeague();
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String args[])throws IOException {
while(true){
System.out.println("Welcome to the NHL statistic program");
System.out.println("Would you like to proceed to the program? <y for yes, n for no>");
final String menuDecision = br.readLine();
if (menuDecision.equals("n")) {
System.out.println("Goodbye");
System.exit(0);
}
if (menuDecision.equals("y")) {
while(true) {
System.out.println("The 8 teams are Toronto Maple Leafs, Montreal Canadiens, Ottawa Senators, Detroit Red Wings, Boston Bruins,"+
" Chicago Blackhawks, New York Islanders, and Pitsburg Penguins");
System.out.println("To input statistics for Toronto, enter '0' ");
System.out.println("To input statistics for Montreal, enter '1' ");
System.out.println("To input statistics for Ottawa, enter '2' ");
System.out.println("To input statistics for Detroit, enter '3' ");
System.out.println("To input statistics for Boston, enter '4' ");
System.out.println("To input statistics for Chicago, enter '5' ");
System.out.println("To input statistics for New York, enter '6' ");
System.out.println("To input statistics for Pitsburg, enter '7' ");
int numString = Integer.parseInt(br.readLine());
Info (numString);
}
}
}
}
public static double[][] Info(int teamInput)throws IOException{
System.out.println("Enter the amount of games played");
int games = Integer.parseInt(br.readLine());
HockeyChart [0+teamInput][1] = games;
System.out.println("Enter the amount of wins");
int wins = Integer.parseInt(br.readLine());
HockeyChart [0+teamInput][2] = wins;
System.out.println("Enter the amount of ties");
int ties = Integer.parseInt(br.readLine());
HockeyChart [0+teamInput][3] = ties;
System.out.println("Enter the amount of losses");
int losses = Integer.parseInt(br.readLine());
HockeyChart [0+teamInput][4] = losses;
System.out.println("Enter the amount of goals scored");
int goals = Integer.parseInt(br.readLine());
HockeyChart [0+teamInput][5] = goals;
for (int i = 0; i < Rows; i ++) {
for (int j = 0; j < Cols;j ++) {
System.out.println(HockeyChart[i][j] + " ");
}
System.out.println(" ");
}
return HockeyChart;
}
}
This is the program I came up with. I dont understand why I get an output that is a long vertical row of numbers instead of row of numbers side by side.
Any help would be appreciated! thanks
In your Info method, while iterating over arrays, you are using System.out.println(), instead of that you will need to use System.out.print() method.
for (int i = 0; i < Rows; i ++) {
for (int j = 0; j < Cols;j ++) {
System.out.print(HockeyChart[i][j] + " ");
}
System.out.println();
}
Second println statement will help you to move to next line after one row is printed.
Take a look at your loop:
for (int j = 0; j < Cols;j ++) {
System.out.println(HockeyChart[i][j] + " ");
}
println is short for Print Line - it prints the given string, and then moves on to the next line. If you want to print all the contents of the array in a single line, you could use System.out.print instead:
for (int j = 0; j < Cols;j ++) {
System.out.print(HockeyChart[i][j] + " ");
}
You are using System.out.println which means print in new line.
You can use System.out.print for same line i.e horizontal row.
Code will be like this
for (int i = 0; i < Rows; i ++)
{
for (int j = 0; j < Cols;j ++) {
System.out.print(HockeyChart[i][j] + " ");
}
System.out.println(" ");
}
return HockeyChart;
Hey guys I have to write a program for class that asks me to produce a bar graph based on how many cars a salesperson sold for the month. An example is this:
Pam XXXX
Leo XXXXXX
I'm almost there but not quite. As of right now I can get one X next to the salespersons name but any others are printed underneath on separate lines.
Pam X
X
X
If you can help me get those other X's on the same line I would really appreciate it. Thank you for your input!
import java.util.Scanner;
public class BarGraph
{
public static int Pam = 0;
public static int Leo = 0;
public static int Kim = 0;
public static int Bob = 0;
public static Scanner kb = new Scanner(System.in);
public static void main(String args[])
{
System.out.println("Enter number of cars sold by Pam ");
Pam = kb.nextInt();
kb.nextLine();
System.out.println("Enter number of cars sold by Leo ");
Leo = kb.nextInt();
kb.nextLine();
System.out.println("Enter number of cars sold by Kim ");
Kim = kb.nextInt();
kb.nextLine();
System.out.println("Enter number of cars sold by Bob ");
Bob = kb.nextInt();
kb.nextLine();
System.out.print("Pam "); pamsCars();
System.out.print("Leo "); leosCars();
System.out.print("Kim "); kimsCars();
System.out.print("Bob "); bobsCars();
}
public static void leosCars()
{
for(int i=0; i < Leo; i++)
{
printX();
}
}
public static void kimsCars()
{
for(int i=0; i < Kim; i++)
{
printX();
}
}
public static void pamsCars()
{
for(int i=0; i < Pam; i++)
{
printX();
}
}
public static void bobsCars()
{
for(int i=0; i < Bob; i++)
{
printX();
}
}
public static void printX()
{
System.out.println("X");
}
}
You are using System.out.println("X"); This automatically appends a newline character to the end of the string.
Instead use System.out.print("X"); to print the X's next to each other.
couldn't you use a
System.out.printf("%s",x);
as well?
or
System.out.printf("%n%s",x);
i didn't try the loop myself but i'm pretty sure one of the two would also be an alternative... the %n will give you the same result as println as long as you go with printf and %n... its the same escape sequence as \n when you're using println.
i just learned that a month ago in class, so i figured i'd share what basic knowledge i have... mid-terms next week so i have programming fever.
use print instead of println in your printX function to be specific.
since println prints and adds break (newline)
public static void printX()
{
System.out.println("X"); // println() puts newline character.. use print()
}
Change your printX() method not to print newline and change the printCar() signature to accept name and number of X to print.
public static void printX()
{
System.out.print("X");
}
public static void printCars(String name, int num)
{
System.out.print(name);
for(int i=0; i < num; i++)
{
printX();
}
System.out.println();
}
Now you can call them like
printCars("Pam ",Pam));
printCars("Bob ",Bob));
make these changes:
System.out.print("Pam "); pamsCars();System.out.println("");
and
public static void printX()
{
System.out.print("X");
}
As the others have said, the "println()" method adds a "\n" to the end of the line.
How about the following (sorry not tested, so in principle only and more of a meansd of shjowing an alternative to loops).
Of course a flaw is that a user could input more than 10.
There again what if the user input 10,000? (would you really want to print 10,000 X's). Perhaps something to think about.
import java.util.Scanner;
public class BarGraph
{
public static int Pam = 0;
public static int Leo = 0;
public static int Kim = 0;
public static int Bob = 0;
public static Scanner kb = new Scanner(System.in);
//Assume max sales of 10
public static final String maxsales = "XXXXXXXXXX"; //+++++NEW
public static void main(String args[])
{
System.out.println("Enter number of cars sold by Pam ");
Pam = kb.nextInt();
kb.nextLine();
System.out.println("Enter number of cars sold by Leo ");
Leo = kb.nextInt();
kb.nextLine();
System.out.println("Enter number of cars sold by Kim ");
Kim = kb.nextInt();
kb.nextLine();
System.out.println("Enter number of cars sold by Bob ");
Bob = kb.nextInt();
kb.nextLine();
printCars("Pam",pam); //+++++NEW
printCars("Leo",leo); //+++++NEW
printCars("Kim",kim); //+++++NEW
printcars("Bob",bob); //+++++NEW
}
//+++++NEW All other methods/functions replaced by this one
public static void printCars(String person, int sales) {
system.out.println(person + " " + maxsales.substr(sales));
}
}
// Incrementing by one in Java
for (int i=0; i<10; i++) {
System.out.println(i);
}
// Incrementing by one
// Printing Horizontally
for (int i=0; i<10; i++) {
System.out.print(" " + i);
}
int n = 20;
for(int i = 0; i <= n; i++) {
System.out.print(" " + i);
}
I want to be able to enter a string s and an integer n, then print the string s n times. I have done this, but I want there to be only 2 strings per line.
Here is my code so far:
public static void main(String[]args){
Scanner in = new Scanner(System.in);
System.out.println("Please enter string: ");
String s = in.nextLine();
System.out.println("Please enter number: ");
int n = in.nextInt();
for(int j=0; j<n; j++){
System.out.println(s);
}
if(n<0){
System.out.println("error: number must be positive");
}
}
Let's say the string was java and the number was 6. I need it to output:
java java
java java
java java
Use the modulo operator (%) to check if your loop index is evenly divisible by 2.
public static void main(String[]args){
Scanner in = new Scanner(System.in);
System.out.println("Please enter string: ");
String s = in.nextLine();
System.out.println("Please enter number: ");
int n = in.nextInt();
for(int j=1; j<n+1; j++){
System.out.print(s);
if (j%2==0)
System.out.println("\n");
else
System.out.print(" ");
}
if(n<0){
System.out.println("error: number must be positive");
}
}
EDIT I changed the output to use print() instead of println() and added an empty space so the output is formatted as the example in your question. Also changed the for loop index to be one based so the mod works correctly.
Create a simple counter that counts to two inside your for loop. After it reaches two. Add a return character.
int count = 0;
for(int j=0; j<n; j++){
System.out.print(s);
count++;
if (count == 2) {
System.out.print("\n");
count = 0;
}
}
for(int j=0; j<n/2; j++){
System.out.println(s+" "+s);
}
public static void main(String[]args){
Scanner in = new Scanner(System.in);
System.out.println("Please enter string: ");
String s = in.nextLine();
System.out.println("Please enter number: ");
int n = in.nextInt();
for(int j=0; j<n; j++){
// modified
if(j%2==0 && j!=0){
System.out.println("\n");
}
System.out.print(s); // Should this not be print and not println
System.out.print(" ");
// end of modification
}
if(n<0){
System.out.println("error: number must be positive");
}
}
Try this code
public static void main(String[]args){
Scanner in = new Scanner(System.in);
System.out.println("Please enter string: ");
String s = in.nextLine();
System.out.println("Please enter number: ");
int n = in.nextInt();
for(int j=0; j<n/2; j++){
System.out.print(s + " " + s + "\n");
}
if(n%2 == 1){
System.out.print(s);
}
if(n<0){
System.out.println("error: number must be positive");
}
}
I am working in a small task that allow the user to enter the regions of any country and store them in one array. Also, each time he enters a region, the system will ask him to enter the neighbours of that entered region and store these neighbours.
I did the whole task but I have small two problems:
when I run the code, the program does not ask me to enter the name of the first region
(This is happened only to the first region)
I could not be able to print each region and its neighbours like the following format:
Region A: neighbour1 neighbour2
Region B: neighbour1 neighbour2
and so on.
My code is the following:
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class Test6{
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.print("Please enter the number of regions: ");
int REGION_COUNT = kb.nextInt();
String[][] regions = new String[REGION_COUNT][2];
for (int r = 0; r < regions.length; r++) {
System.out.print("Please enter the name of region #" + (r+1) + ": ");
String region = kb.nextLine();
System.out.print("How many neighbors for region #" + (r+1) + ": ");
if (kb.hasNextInt()) {
int size = kb.nextInt();
regions[r] = new String[size];
kb.nextLine();
for (int n = 0; n < size; n++) {
System.out.print("Please enter the neighbour #"
+ (n) + ": ");
regions[r][n] = kb.nextLine();
}
} else System.exit(0);
}
for(int i=0; i<REGION_COUNT; i++){
for(int k=0; k<2; k++){
System.out.println(regions[i][k]);
}
}
}
}
Thanks everybody for your immediate helps. But let me explain to you what I want in more details.
First of all, I need to use the two dimensional array.
Secondly, my problem now is just with the printing of the result. I want to print the results like the following format:
> RegionA : its neighbours
For example, let us take USA
> Washington D.C: Texas, Florida, Oregon
--------------------------------------------------------------------------
Dear ykartal,
I used your program and it gave me the following:
when I run the code, the program
does not ask me to enter the name of
the first region (This is happened
only to the first region)
Because you are using nextLine, program take your first edit for nextLine use next insteadof nextline
could not be able to print each region and
its neighbours like the following
format: Region A: neighbour1
neighbour2 Region B: neighbour1
neighbour2 and so on.
A and B is the name or Alphabetic order of regions? If alphabetics 65 is the aSCII equalence of 'A' and 66 is 'B' ... So using (char)65 write A. Otherwise put region names instead of (char)65+i
Try this;
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class Test6{
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.print("Please enter the number of regions: ");
int REGION_COUNT = kb.nextInt();
String[] regionNames = new String[REGION_COUNT];
String[][] regions = new String[REGION_COUNT][2];
for (int r = 0; r < regions.length; r++) {
System.out.print("Please enter the name of region #" + (r + 1)
+ ": ");
regionNames[r] = kb.next();
System.out
.print("How many neighbors for region #" + (r + 1) + ": ");
if (kb.hasNextInt()) {
int size = kb.nextInt();
regions[r] = new String[size];
for (int n = 0; n < size; n++) {
System.out.print("Please enter the neighbour #" + (n)
+ ": ");
regions[r][n] = kb.next();
}
} else
System.exit(0);
}
for (int i = 0; i < REGION_COUNT; i++) {
System.out.print(regionNames[i] +": ");
for (int k = 0; k < 2; k++) {
System.out.print(regions[i][k]+", ");
}
System.out.println();
}
}
}
Output;
Please enter the number of regions: 2
Please enter the name of region #1: aaa
How many neighbors for region #1: 1
Please enter the neighbour #0: a1
Please enter the name of region #2: bbb
How many neighbors for region #2: 2
Please enter the neighbour #0: b1
Please enter the neighbour #1: b2
aaa: a1
bbb: b1 b2
Note: This is not a good code, you must handle if user enter alfanumeric characters instead of numbers where you expected user will enter numeric values.
UPDATE:
This is what you want:
for (int i = 0; i < region.length; i++){
StringBuilder sb = new StringBuilder();
sb.append(region[i] + ": ");
for (int i2 = 0; i2 < neighbor.length; i2++){
if (i2 != 0 && i2 != neighbor.length-1){
sb.append(", " + neighbor[i2]);
}else{
sb.append(neighbor);
}
}
System.out.println(sb.toString());
}
I think it's going to be easier for you if you manipulate your information in a Map.
Try this
Map<String, List<String>> mapRegionNeighbor = new HashMap<String, List<String>>();
System.out.println("What region would you like to see?");
String regionName = scanner.nextLine();
List<String> neighborList = mapRegionNeighbor.get(regionName);
for(String neighbor : neighborList){
System.out.println(regionName + ": " + neighbor);
}
So, basically, if you want to add information to regions:
if it's a new region do this
mapRegionNeighbor.put(regionName, new ArrayList<String>);
if region has got a list of neighbor already, you'll do this to add a new neighbor:
List<String> neighborList = mapRegionNeighbor.get(regionName);
neighborList.add(neighborName);
mapRegionNeighbor.put(regionName, neighborList);
This 3 lines above will just update your region.
To run thru all values printing there neighbors, do something like this:
Iterator it = countedWords.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
for (String neighbor : pairs.getValue()){
System.out.println(pairs.getKey() + ": " + neighbor);
}
}