Display string horizontally or in row Java - java

So I am working on a slot machine on Java using only the console. I have some strings with ASCII word art that must be displayed on blocks of three, horizontally, like a slot machine.
static final String pera = " ( \n / \\ \n ( ) \n `\"' \n \n";
static final String platan = " \n , \n \\`.__.\n `._,'\n \n";
static final String raim = " \\ \n ()() \n()()()\n ()() \n () \n";
static final String kiwi = " \n,=. \n(.`:) \n `-' \n";
static final String penaut = " ,+. \n((|)) \n )|( \n((|)) \n `-' ";
So right now this is the output
And I need it to look like this target output
The problem is that the strings I'm using are not just 1 line strings, so the usuall methods to print on the same line doesn't work, like using print instead of println. Is this even possible to program on java?
Complete code:
package Escurabutxaques;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class Escurabutxaques {
static boolean correcte = false;
static String res1 = "";
static String res2 ="";
static String res3 = "";
static final String pera = " ( \n / \\ \n ( ) \n `\"' \n \n";
static final String platan = " \n , \n \\`.__.\n `._,'\n \n";
static final String raim = " \\ \n ()() \n()()()\n ()() \n () \n";
static final String kiwi = " \n,=. \n(.`:) \n `-' \n";
static final String penaut = " ,+. \n((|)) \n )|( \n((|)) \n `-' ";
public static void main (String[] Args){
System.out.println("Benvingut a la màquina escurabutxaques de l'Andreu!");
Random();
}
public static void Random() {
for (int i = 0; i < 3; ++i) {
String print = "";
Random r = new Random();
int randomNumber = ThreadLocalRandom.current().nextInt(1, 5 + 1);
if (randomNumber == 1) {
print = pera;
switch (i){
case 1:
res1 = print;
break;
case 2:
res2 = print;
break;
case 3:
res3 = print;
break;
}
} else if (randomNumber == 2) {
print = raim;
switch (i){
case 1:
res1 = print;
break;
case 2:
res2 = print;
break;
case 3:
res3 = print;
break;
}
} else if (randomNumber == 3) {
print = platan;
switch (i){
case 1:
res1 = print;
break;
case 2:
res2 = print;
break;
case 3:
res3 = print;
break;
}
} else if (randomNumber == 4) {
print = kiwi;
switch (i){
case 1:
res1 = print;
break;
case 2:
res2 = print;
break;
case 3:
res3 = print;
break;
}
} else if (randomNumber == 5) {
print = penaut;
switch (i){
case 1:
res1 = print;
break;
case 2:
res2 = print;
break;
case 3:
res3 = print;
break;
}
};
System.out.println(print);
Random();
}
}
}

You want to print three different things, and each thing is going to take up multiple rows, and you want the three things to appear side by side. There is a way to do this:
make sure each of your possible items to show is built of the same number of rows, and each row is of the same width
build each item as an array of strings, where each string in the array is one of the required rows of symbols:
String[] apple = new String[5];
apple[0] = ",./.,/";
apple[1] = "/dkj/!";
etc
or whatever the apple looks like.
run code to determine which three items should be displayed, e.g. apple banana apple
write an output builder which knows at the start what three things it needs to put together, in this case an apple followed by a banana followed by another apple. This output builder will return an array of Strings, where row in the array is composed of the corresponding rows from the component objects.
String[] outputToDisplay = new String[5];
outputToDisplay[0] = apple[0] + banana[0] + apple[0];
outputToDisplay[1] = apple[1] + banana[1] + apple[1];
etc
You may wish to insert a blank space between each item in each row.
print the output

I'm identifying that it seems that every fruit String object is composed of 7 characters before it goes onto the next line. What you could do is simply take out the first 7 characters of the first fruit, then go on to the next fruit and take out the next 7 characters of the next fruit and concatenate these two Strings together. Keep on continuing this until you've reached the final fruit. You can then save the String which represents the first line in an array. Then you can simply move on the next 7 characters(a.k.a the second line) and repeat the process all over again. After you've gone through all the fruits, simply print out the string array.

Try ANSI cursor movement.
Here is an example code to print two slots.
After understanding the trick, you can easily expand it to print three slots.
private static void printSlots(String slot1, String slot2) {
int m = 0;
int n = 0;
for (String line : slot1.split("\n")) {
System.out.println(line);
m = m > line.length() ? m : line.length();
n += 1;
}
System.out.print("\033[" + n + "A"); // ANSI cursor movement to up
for (String line : slot2.split("\n")) {
System.out.print("\033[" + m + "C"); // ANSI cursor movement to right
System.out.println(line);
}
}
After printing n lines, it goes back. Then, it print each line of next slot with left m paddings.

Related

How to remove one charachter from a string

With the scanner I want to read the index of a char and then remove it from the string. There is only one problem: If the char comes multiple times in the string, .replace() removes all of them.
For example I want to get the index of first 't' from the String "Texty text" and then remove only that 't'. Then I want to get index of second 't' and then remove it.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
String text = "Texty text";
Scanner sc = new Scanner(System.in);
int f = 0;
int x = 0;
while(f<1){
char c = sc.next().charAt(0);
for(int i = 0; i<text.length();i++){
if(text.charAt(i)==c){
System.out.println(x);
x++;
}
else{
x++;
}
}
}
System.out.println(text);
}
}
You could use replaceFirst:
System.out.println(text.replaceFirst("t", ""));
Probably you are looking for something like the following:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String text = "Texty text";
String copy = text;
Scanner sc = new Scanner(System.in);
while (true) {
text = copy;
System.out.print("Enter a character from '" + text + "': ");
char c = sc.next().charAt(0);
for (int i = 0; i < text.length(); i++) {
if (Character.toUpperCase(text.charAt(i)) == Character.toUpperCase(c)) {
System.out.println(c + " was found at " + i);
text = text.substring(0, i) + "%" + text.substring(i + 1);
System.out.println("After replacing " + c + " with % at " + i + ": " + text);
}
}
}
}
}
A sample run:
Enter a character from 'Texty text': x
x was found at 2
After replacing x with % at 2: Te%ty text
x was found at 8
After replacing x with % at 8: Te%ty te%t
Enter a character from 'Texty text': t
t was found at 0
After replacing t with % at 0: %exty text
t was found at 3
After replacing t with % at 3: %ex%y text
t was found at 6
After replacing t with % at 6: %ex%y %ext
t was found at 9
After replacing t with % at 9: %ex%y %ex%
Enter a character from 'Texty text':
Try using txt.substring(x,y)
x = usually 0 , but x is first start index
y = this is what you want to delete for example for the last word of string write this code:
txt.substring(0, txt.length() - 1)
Since you are specifying indices, it is possible that you may want to replace the second of a particular character. This does just that by ignoring the ones before it. This returns an Optional<String> to encase the result. Exceptions are thrown for appropriate situations.
public static void main(String[] args) {
// Replace the first i
Optional<String> opt = replace("This is a testi", 1, "i", "z");
// Replace the second i (and so on).
System.out.println(opt.get());
opt = replace("This is a testi", 2, "i", "z");
System.out.println(opt.get());
opt = replace("This is a testi", 3, "i", "z");
System.out.println(opt.get());
opt = replace("This is a testi", 4, "i", "z");
System.out.println(opt.get());
}
public static Optional<String> replace(String str, int occurrence, String find, String repl) {
if (occurrence == 0) {
throw new IllegalArgumentException("occurrence <= 0");
}
int i = -1;
String strCopy = str;
while (occurrence-- > 0) {
i = str.indexOf(find, i+1);
if (i < 0) {
throw new IllegalStateException("insufficient occurrences of '" + find + "'");
}
}
str = str.substring(0,i);
return Optional.of(str + strCopy.substring(i).replaceFirst(find, repl));
}

Trying to work off and input by the user to change a value

I am creating a small game-type program,
Firstly I'm asking the user to give his name,
Secondly, I'm asking the user to choose one of the spaceships,
Thirdly, I want the user to add 2 modification, to improve the stats...
Here is the problem, I want to change some values of the spaceship.
The problem is that I don't know how to determine the chosen spaceship and how to change its values. Example: The Heavy-type Armour is 90 right now​ if I add the Advanced Hull Armour modification, i want it to increase to 100
public class Game {
static void playerName() {
System.out.println("What's your name?:");
String name = Keyboard.readString();
System.out.println("Okay,"+name+" it is!\n");
}
static class StarShip {
String name;
String armour;
String attack;
String mobility;
}
public static void main (String args[]) {
System.out.println("Hello Rookie! \n");
playerName();
System.out.println("Let's pick your first ship!\n");
System.out.println("Choose one of these:");
//insert ships here:
StarShip ship1 = new StarShip();
ship1.name = "Heavy-type";
ship1.armour = "Armour=90";
ship1.attack = "Firepower=50";
ship1.mobility = "Mobility=40";
StarShip ship2 = new StarShip();
ship2.name = "Medium-type";
ship2.armour = "Armour=60";
ship2.attack = "Firepower=60";
ship2.mobility = "Mobility=60";
StarShip ship3 = new StarShip();
ship3.name = "Light-type";
ship3.armour = "Armour=20";
ship3.attack = "Firepower=60";
ship3.mobility = "Mobility=90";
System.out.println("1 -"+ship1.name+"- "+ship1.armour+" "+ship1.attack+" "+ship1.mobility);
System.out.println("2 -"+ship2.name+"- "+ship2.armour+" "+ship2.attack+" "+ship2.mobility);
System.out.println("3 -"+ship3.name+"- "+ship3.armour+" "+ship3.attack+" "+ship3.mobility);
int chosen = Keyboard.readInt();
switch (chosen) {
case 1:
System.out.println("Heavy-type! Excellent choice! Great armour and guns! \n");
break;
case 2:
System.out.println("Medium-type! An all-rounder, a mix of everything! \n");
break;
case 3:
System.out.println("Light-type! Fast and mobile, but has little armour! \n");
break;
}
System.out.println("Lets pimp out your ship! \n");
String advancedHull = "1 - Advanced Hull Armour - Armour +10";
String betterAmmo = "2 - Better Ammo \t - Firepower +10";
String booster = "3 - Booster \t\t - Mobility +10";
System.out.println(advancedHull+"\n"+betterAmmo+"\n"+booster);
}
}
Currently you the fields of the StarShip are all Strings, when you add two strings they are concatenated, eg "abc"+"def" = "abcdef" regardless of what they say. You want to use ints these are "java numbers" and add as you would expect eg 10 + 20 = 30
class StarShip {
String name;
int armour;
int attack;
int mobility;
}
...
StarShip ship1 = new StarShip();
ship1.name = "Heavy-type";
ship1.armour = 90;
ship1.attack = 50;
ship1.mobility = 40;
...
When the user selects the ship we want to save this chose into a variable, like so:
Starship chosenShip; // must be declared outside the switch statement
switch (shipChoice ) {
case 1:
System.out.println("Heavy-type! Excellent choice! Great armour and guns! \n");
chosenShip = ship1;
Break;
...
Assuming advancedHull is selected and you include logic similar to how ships are selected
if (modificationChoice = 1){
chosenShip.armour = chosenShip.armour + 10;
} ...
You may want to declare a toSting() methods in StarShip like so
#Override
public String toString() {
return name +" Armour=" + armour +", Firepower=" + attack +", Mobility=" + mobility;
}
This way you can call System.out.println(ship1.toString()) to print the ship info.
Example:
System.out.println(ship1.toString());
// outputs: Heavy-type Armour=90, Firepower=50, Mobility=40
ship1.armour += 10; // java shorthand for `ship1.armour + ship1.armour + 10`
System.out.println(ship1.toString());
// outputs: Heavy-type Armour=100, Firepower=50, Mobility=40

Issue regarding Methods and Classes, Non-Static Error and more

I am trying to develop a simple program that will take inputs 1-11 from a user and digest them within a class and output a clean printed statement that will change based on these inputs.
Here is some of my current code.
public static void main(String[] args) {
mainInputMenu();
}
private static void mainInputMenu() {
System.out.println ( "=======================================\n"
+ "Welcome to the Ticket Counter\n"
+ "1. Approach first machine.\n"
+ "2. Approach Second machine\n"
+ "3. Exit." );
Scanner keyboard = new Scanner ( System.in );
String ticketCounter;
int counter = 0;
//I have a do while statement which confirms input but irrelevant
while ( counter == 1 ) {
machineOne ( counter );
}
while ( counter == 2 ) {
machineTwo ( counter );
}
while ( counter == 3 ) {
System.exit(0);
}
}
public static void machineOne(int counter) {
Scanner keyboard = new Scanner ( System.in );
String ticketInput;
int choice = 0;
TheMachine machineOne = new TheMachine();
TheMachine.writeOutput();
switch ( choice ) {
case 1:
machineOne.option = 1;
break;
case 2:
machineOne.option = 2;
break;
case 3:
machineOne.option = 3;
}
}
This is the main program with up to only 3 options at the moment. Now going into what I don't understand... I can attempt to move through this via a method I thought may possibly work being to create sub-components of this class to do the work and print those variables within the writeOutput(). Which results in non-static method cannot be referenced from static context error like below.
public class TheMachine {
public static void writeOutput() {
System.out.println ( " ------------------------------------------\n");
System.out.println ( "Adults: " + getadultSum() ); //Simplified to show the issue
public int getadultSum () {
switch ( option ) {
case 3:
adultSum = adultSum + 1;
return adultSum;
case 4:
adultSum = adultSum - 1;
return adultSum;
}
Or my first attempt solution which was to make a switch based on the option variable to change these different variables. Some include # of Adults, # of Children, Dollar Amount entered, etc.
static void writeOutput()
{
int childTickets = 0;
int adultTickets = 0;
String route = "";
int childSum = 0;
int adultSum = 0;
int creditSum = 0;
switch (choice) {
case 1:
route = "Uptown";
break;
case 2:
route = "Downtown";
break;
case 3:
adultSum = adultSum + 1;
break;
default:
break;
}
But this issue I run into with this one, I mean it works once around but every time you enter a new input the variable is reset to 0.
If anybody takes the time to read through this and can provide me with some help, bless you. I appreciate all your time and efforts.

Converting parts of Strings to Character to be used in if/else statements

I'm doing an assignment in school and although I've checked through the entire written material I cannot for the life of me find out how to do this. We are supposed to enter strings like "0123 B" and the B at the end of the string is suppose to represent bronze and then add ++ to the Bronze integer. Then print the number of medals.
My issue here is that I'm trying to take the final character from the string (B, S, or G) and then add to that, but the thing is, it's a String and not a character. So I can't use medal.charAt(5).
Here is my code below:
EDITED, CODE IS SOLUTION
import java.util.Scanner;
public class CountMedals {
public static void main(String[] args) {
int bronze = 0;
int silver = 0;
int gold = 0;
int totalMedals = 0;
int incorrectMedals = 0;
char gol = 'G';
char sil = 'S';
char bro = 'B';
String medal = " ";
Scanner in = new Scanner(System.in);
System.out.println("Please enter the event number followed by the first letter of the medal type." +
" (I.E. \"0111" + " B\"). Type exit once completed");
while (!medal.equals("")) {
medal = in.nextLine();
if (medal.charAt(medal.length() - 1) == bro)
{
bronze++;
totalMedals++;
}
else if (medal.charAt(medal.length() - 1) == sil)
{
silver++;
totalMedals++;
}
else if (medal.charAt(medal.length() - 1) == gol)
{
gold++;
totalMedals++;
}
else if (medal.equals("exit"))
{
System.out.println("Gold medals: " + gold);
System.out.println("Silver medals: " + silver);
System.out.println("Bronze medals: " + bronze);
System.out.println("Total medals: " + totalMedals);
System.out.println(incorrectMedals + " incorrect medal(s) entered.");
}
else{
incorrectMedals++;
}
}
}
}
Just make gol, sil, and bro into chars instead of Strings.
char gol = 'G';
char sil = 'S';
char bro = 'B';
After that change, you should be able to use
medal.charAt(5) == gol
no problem.
Edit
To make this even more generic, you could use
medal.charAt(medal.length() - 1) == gol
which will always pull the last character, thereby avoiding errors with input that has less than 5 indices.

Counting the occurrences of a String in an ArrayList

I'm using an ArrayList to save the name, day and time of a show. My program requires me to output the number of shows that play on each day of the week. I've inputted 4 different shows, two of which are on the same day. So far, the only thing the output's given me is "On Thursday there are/is 2 show(s)." The other two didn't show. How can I make is so that it displays the number of shows for each day I've inputted? Here's my code for that:
String showDay = ((showInfo)show.get(0)).day.toString();
int totalShows = 0;
//print occurences for how many shows play each day
for (int i = 0; i < show.size(); i++) {
if (showDay.equals(((showInfo)show.get(i)).day.toString())) {
totalShows++;
}
}
System.out.println("On " + showDay + " there are/is " + totalShows + " show(s).");
}
Here's my code for the shows I input:
//input information
do{
showInfo temp = new showInfo();
System.out.print("Enter the name of show: ");
String showName = br.readLine();
temp.name = showName;
System.out.print("Enter which day of the week a new episode premieres: ");
String showDay = br.readLine();
temp.day = showDay;
System.out.print("Enter time in 24-hour format (e.g. 2100, 1900): ");
int showTime = Integer.valueOf(br.readLine()).intValue();
temp.time = showTime;
show.add(temp);
System.out.print("Would you like to add another show? (y/n) ");
}
while((br.readLine().compareTo("n")) != 0);
Keep in mind that I'm using Java 1.4. No other choice. By teacher's demand.
This is probably obvious, but I'm being oblivious right now. Any help would be great! Thanks in advance!
EDIT:
String showDay = ((showInfo)show.get(0)).day.toString();
if("sunday".equalsIgnoreCase(showDay)){
showdayCount[0]++;
System.out.println("There are/is " + showdayCount[0]++ + " show on Sunday.");
}else if("monday".equalsIgnoreCase(showDay)){
showdayCount[1]++;
System.out.println("There are/is " + showdayCount[1]++ + " show on Monday.");
}else if("tuesday".equalsIgnoreCase(showDay)){
showdayCount[2]++;
System.out.println("There are/is " + showdayCount[2]++ + " show on Tuesday.");
}else if("wednesday".equalsIgnoreCase(showDay)){
showdayCount[3]++;
System.out.println("There are/is " + showdayCount[3]++ + " show on Wednesday.");
}else if("thursday".equalsIgnoreCase(showDay)){
showdayCount[4]++;
System.out.println("There are/is " + showdayCount[4]++ + " show on Thursday.");
}else if("friday".equalsIgnoreCase(showDay)){
showdayCount[5]++;
System.out.println("There are/is " + showdayCount[5]++ + " show on Friday.");
}else if("saturday".equalsIgnoreCase(showDay)){
showdayCount[6]++;
System.out.println("There are/is " + showdayCount[6]++ + " show on Saturday.");
}
This is also only giving me one line. What am I doing wrong?! :(
EDIT:
What I want is to input name/day/time of a TV show, then later be able to display the amount of shows that are on that specific day!
For example, Big Bang Theory and Community are both on Thursday. So the code would output something like
There are 2 shows on Thursday.
Nothing's worked, so far.
You only get one day from this line:
String showDay = ((showInfo)show.get(0)).day.toString();
Here's my hack solution (may have some errors, like a misnamed variable but you should be able to fix it):
//Create a map that maps days to the shows that are on that day
LinkedHashMap showDays=new LinkedHashMap(); //String to Set map
String[] days={"Sunday","Monday", ....};//put the rest of the days in here
for(int dayIndex=0;dayIndex<days.length;dayIndex++){
String day=days[dayIndex];
showDays.put(day,new HashSet());
}
//iterate through the shows and put them in their respective days in the map
for (int i = 0; i < show.size(); i++) {
String dayForShow=((showInfo)show.get(i)).day.toString();
showDays.get(dayForShow).put(show.get(i));
}
//now print out how many shows are on each day
for(int dayIndex=0;dayIndex<days.length;dayIndex++){
String day=days[dayIndex];
int showsToday=showDays.get(day).size();
///do your print out now
}
You can make 'LinkedHashMap showDays' a class variable and add to it each time you add to show (and remove from it each time you remove from show).
PS. Tell your teacher it is no longer 2002, technology moves on and they make my job harder.
Create a Show class
public class Show {
String showName;
String showDay;
int showTime;
static int[] showdayCount = new int[7];
public Show(String showName, String, showDay, iny showTime){
this.showName = showName;
this.showDay = showDay;
this.showTime = showTime;
// increment showDayCOunt[] according to showDay from
switch(showDay){
case "Sunday": showDayCount[0]++; break;
case "Monday": showDayCount[1]++; break;
case "Tuesday": showDayCount[2]++; break;
case "Wednesday": showDayCount[3]++; break;
case "Thursday": showDayCount[4]++; break;
case "Friday": showDayCount[5]++; break;
case "Saturday": showDayCount[6]++; break;
}
}
}
Here's your main method from YourClass
public static void main(String[] args){
// Create Array of Shows
Show[] shosList = new Show[4]; // or how many ever shows you have
// Get your inputs for showName, showDay, showTime
Sting showName =
String showDay =
int showTime =
// Create show Object
Show show = new Show(showName, showDate, showTime);
// add show to ArrayList
showList[someIndex] = show;
// Do all other stuff then print
// when you print, you can get the showDayCount directly from the Show class
}
Now I don't want to do everything for you. I just want to get you headed in the right direction. Note that if you want the above to happen more than once, consider putting inside of a loop.
Edit: With getShowdayCount
Add this to my above Show class
public int getShowdayCount(String showday){
switch(showDay){
case "Sunday": return showDayCount[0]; break;
case "Monday": return showDayCount[1]; break;
case "Tuesday": return showDayCount[2]++; break;
case "Wednesday": return showDayCount[3]++; break;
case "Thursday": return showDayCount[4]++; break;
case "Friday": return showDayCount[5]++; break;
case "Saturday": return showDayCount[6]++; break;
}
}
Edit: With example if/else if from switch statement
// for main method inputs
if ("sunday"equalsIgnoreCase(showDay){
showdayCount[0]++
} else ("monday".equalsIgnoreCase(showDay){
showdayCount[1]++
} // finish if/else if statement
// for getShowdayCount method
if ("sunday"equalsIgnoreCase(showDay){
return showdayCount[0];
} else ("monday".equalsIgnoreCase(showDay){
return showdayCount[1];
} // finish if/else if statement
You can call it from your main class like this
show.getShowdayCount(show.showday);
Edit: Actually, Just put the above edit in you class with the main method
YourClassWithMainMethod{
static int[] showdayCount = new int[7];
public static void mina(String[] args){
// call getShowdayCount here
getShowdayCount(String showday);
}
public static int getShowdayCount(String showday){
}
}
Edit: What you do want and what you don't want
You dont need this in you if statement
System.out.println("There are/is " + showdayCount[5]++ + " show on Friday.");
When you want to print all the shows:
for (int i = 0; i < showdayCount.length; i++){
int showday;
if (i == 0){
showday = "Sunday
finish the if/else if statements
}
System.out.println("There is " + showDayCount[i] + " shows on " + showday);
}

Categories

Resources