Print String in Inverse Pyramid - java

Scanner scnr = new Scanner(System.in);
String x;
int y;
System.out.println("Enter the String : ");
x = scnr.nextLine();
y = x.length();
for(int i=0; i<y; i++) {
for(int j=0; j <i; j++) {
System.out.printf("%c ",x.charAt(j));
}
System.out.printf("%c\n",x.charAt(i));
}
If you entered "Kevin" it would print
K
KE
KEV
KEVI
KEVIN going down
I am looking for it to print the full word first and then remove a letter as you go down
thanks

I would just use a simple for loop here:
System.out.println("Enter the String : ");
String x = scnr.nextLine();
for (int i=0; i < x.length(); ++i) {
System.out.println(x.substring(0, x.length()-i));
}
For an input of KEVIN, the output from the above would be:
KEVIN
KEVI
KEV
KE
K

Solution using simple recursion
public static void main(String[] args) {
inversePyramid("KEVIN");
}
public static void inversePyramid(String s){
if(s.length()>1) {
inversePyramid(s.substring(0, s.length()-1));
}
System.out.print(s+" ");
}

If you need to use two-loop then this will be the approach.
System.out.println("Enter the String : ");
x = scnr.nextLine();
for(int i=0;i < x.length(); i++) {
for(int j = 0; j < x.length() - i ; j++) {
System.out.print(x.charAt(j));
}
System.out.println();
}
output:
KEVIN
KEVI
KEV
KE
K

public class Home{
public static void main(String[] args){
Scanner scnr = new Scanner(System.in);
String x;
int y;
System.out.println("Enter the String : ");
x = scnr.nextLine();
y = x.length();
for(int i=0; i<y;i++){
for(int j=0;j<i;j++){
System.out.printf("%c ",x.charAt(j));
}
System.out.printf("%c\n",x.charAt(y-1));
}
}
}

Related

Scan and put it to Array

I want scan sentence and count how many word is. And than put the sentence to Array. And print it.
It works until System.out.println("단어개수 : " + count);
but it doesn't work after that.
import java.util.Scanner;
public class Midterm_HW00 {
public static void main(String[] args) {
System.out.println("Insert sentence: ");
Scanner scanner = new Scanner(System.in);
int count =1;
String sentence = scanner.nextLine(); //문자열 읽기
for(int i = 0; i < sentence.length(); i++) {
if(sentence.charAt(i)==' ') { //단어 개수를 띄어쓰기 개수로 계산
count++;
}
}
System.out.println("단어 개수: " + count);
String[] wordArray = new String[30]; //배열 선언
int word = wordArray.length;
for(int j=0; j<word; j++){
wordArray[j] = scanner.next();
System.out.println("" + wordArray[j]);
scanner.close();
}
}
}
you can get all this by using simple method:
String[] array = yourString.split(" ");
int amountOfWords = array.length;
Scanner scanner = new Scanner(System.in);
String sentence = scanner.nextLine();
String[] words = sentence.split("[ ]+");
System.out.println("단어 개수: " + words.length);
for(String word : words){
System.out.println(word);
}
you can use string split by a space to generate an array like this String[] wordArray = sentence.split("\\s+");
code :
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Insert sentence: ");
Scanner scanner = new Scanner(System.in);
int count =1;
String sentence = scanner.nextLine(); //문자열 읽기
for(int i = 0; i < sentence.length(); i++) {
if(sentence.charAt(i)==' ') { //단어 개수를 띄어쓰기 개수로 계산
count++;
}
}
System.out.println("단어 개수: " + count);
String[] wordArray = sentence.split("\\s+"); //배열 선언
for(int j=0; j<wordArray.length; j++){
System.out.println("" + wordArray[j]);
}
}
import java.util.*;
public class Main {
public static void main(String[] args) {
System.out.println("Insert sentence: ");
Scanner scanner = new Scanner(System.in);
int count =1;
String sentence = scanner.nextLine();
for(int i = 0; i < sentence.length(); i++) {
if(sentence.charAt(i)==' ') {
count++;
}
}
System.out.println("단어 개수: " + count);
String[] wordArray = new String[] {sentence};
for(int j=0; j<count; j++){
System.out.println("" + wordArray[j]);
scanner.close();
}
}
}
import java.util.*;
public class Solution {
public static void main(String [] args) {
Scanner sc = new Scanner(System.in);
int count = 1;
String sentence = sc.nextLine();
// finding the number of word
for (int i=0; i<sentence.length(); i++) {
if (sentence.charAt(i) == ' ')
count += 1;
}
System.out.println("The count is : " + count);
// store the sentence to a string array using split(split by the space)
String [] sentenceToArray = sentence.split(" ");
// print all elements inside the array
for (int i=0; i<sentenceToArray.length; i++)
System.out.print(sentenceToArray[i]);
}
}

Runtime error in java about selection sort

I have learnt selection sort, and i try to code it with java. But it has an error, i think it a runtime error. I don't know what to fix in my code.
This is the code:
import java.util.Scanner;
public class Main {
public static void main(String args[])
{
int temp;
Scanner sc=new Scanner(System.in);
int number;
int input=sc.nextInt();
int [] carriage;
carriage=new int[input];
for(int i=0;i<input;i++)
{
number=sc.nextInt();
carriage[i]=number;
}
int n=carriage.length;
for(int i=0;i<n-1;i++)
{
for(int j=i+1;i<n;j++)
{
if(carriage[j]<carriage[i])
{
temp=carriage[i];
carriage[i]=carriage[j];
carriage[j]=temp;
}
}
System.out.println(carriage[i]+ " ");
}
sc.close();
}
}
I think you want to sort the number of integer provided by user. Your code is having 2 errors. One in the for loop starting with i, the condition should be i
public class Main {
public static void main(String args[]) {
int temp;
Scanner sc = new Scanner(System.in);
int number;
System.out.println("Enter the number of integers to be sorted - ");
int input = sc.nextInt();
int[] carriage;
carriage = new int[input];
for (int i = 0; i < input; i++) {
System.out.println("Enter the "+ i+1 +"number - ");
number = sc.nextInt();
carriage[i] = number;
}
int n = carriage.length;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (carriage[j] < carriage[i]) {
temp = carriage[i];
carriage[i] = carriage[j];
carriage[j] = temp;
}
}
System.out.println(carriage[i] + " ");
}
sc.close();
}
}

Java Crossword 2d Array

package assignment2;
import java.util.Random;
import java.util.Scanner;
public class test2 {
public static void main(String[] args) {
int wordAmount = wordAmount();
String[] words = wordArray(wordAmount);
displayWords(words, wordAmount);
char[][] puzzleGrid = generatePuzzleGrid(words, wordAmount);
//System.out.println(Arrays.deepToString(puzzleGrid)); //just using this to test
printPuzzleGrid(puzzleGrid, wordAmount);
}
public static int wordAmount(){
Scanner input = new Scanner(System.in);
System.out.print("How many words would you like in the word search(5-15): ");
int wordAmount = input.nextInt();
while(wordAmount < 5 || wordAmount > 20){
System.out.println("The number you've requested is either to large or to small.");
System.out.print("How many words would you like in the word search(5-20): ");
wordAmount = input.nextInt();
}
return wordAmount;
}
public static String[] wordArray(int wordAmount){
String[] words = new String[wordAmount];
Scanner input = new Scanner(System.in);
for(int i = 0; i < wordAmount; i++){
System.out.print("Enter a word: ");
words[i] = (input.nextLine().toUpperCase());
for(int j = 0; j < wordAmount; j++){
if(j == i) break;
while(words[i].contains(words[j])){
System.out.print("The word you entered has already been entered, enter a new word: ");
words[i] = (input.nextLine().toUpperCase());
}
}
while(words[i].length() > 10 || words[i].length() <= 2 || words[i].contains(" ")){
System.out.print("The word you entered has been rejected, enter a new word: ");
words[i] = (input.nextLine().toUpperCase());
}
}
return words;
}
public static void displayWords(String[] words, int wordAmount){
System.out.print("The words you must find are: ");
for(int w = 0; w < wordAmount; w++){
System.out.print(words[w] + " ");
}
System.out.println("");
}
public static char[][] generatePuzzleGrid(String[] words, int wordAmount){
char[][] puzzleGrid = new char[wordAmount][wordAmount];
Random rand = new Random();
for(int across = 0; across < wordAmount; across++){
for(int down = 0; down < words[across].length(); down++){
puzzleGrid[across][down] = words[across].charAt(down);
for(int filler = wordAmount; filler >= words[across].length(); filler--){
puzzleGrid[across][filler] = (char)(rand.nextInt(26) + 'A'); //this is the line with the problem
}
}
}
return puzzleGrid;
}
public static void printPuzzleGrid(char[][] puzzleGrid, int wordAmount){
for(int across = 0; across < wordAmount; across++){
for(int down = 0; down < wordAmount; down++){
System.out.print(" " + puzzleGrid[down][across]);
}
System.out.println("");
}
}
}
It seems my last problem has worked itself out, but now I face a new problem.
Error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at assignment2.test2.generatePuzzleGrid(test2.java:63)
at assignment2.test2.main(test2.java:10)
C:\Users\Higle\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 9 seconds)
It seams application runs without any issue only concern is that what will happen if the user provide wordAmount( number of characters in grid ) greater than the word he provided. So it's better to add validation on wordAmount with word length as show on below.
public static char[][] generatePuzzleGrid(String[] words, int wordAmount) {
if(wordAmount>words.length){
wordAmount = words.length;
}
char[][] puzzleGrid = new char[wordAmount][wordAmount];
for (int across = 0; across < wordAmount; across++) {
for (int down = 0; down < words[across].length(); down++) {
puzzleGrid[across][down] = words[across].charAt(down);/////////////////
}
}
return puzzleGrid;
}
It looks like you're calling charAt(5) on a string of less than 5 characters. You can do something like
if(words[across].length() < (down-1)){
continue;
}
to make sure you don't get that particular error... Also, you may like to know charAt() returns the index of a char from 0->length()-1

Getting a weird output on my program lost on what to do next to fix it

So i've ben at this program for awhile and i've gotten everything to work without compiling error but now I'm getting a weird output, first ill post the program the the problem.
import java.util.Scanner;
import java.util.*;
public class project3 {
private static double[] payrate;
private static String[] names;
public static void SortData(double payrate[]) {
int first;
int temp;
int i;
int j;
for (i = payrate.length - 1; i > 0; i--) {
first = 0;
for (j = 1; j <= i; j++) {
if (payrate[j] < payrate[first]) {
first = j;
}
}
temp = (int) payrate[first];
payrate[first] = payrate[i];
payrate[i] = temp;
}
}
public static void GetData() {
Scanner input = new Scanner(System.in);
System.out.println("How many names do you want to enter?");
String strNum = input.nextLine();
int num = Integer.parseInt(strNum);
int array[] = new int[num];
for (int i = 0; i < array.length; i++) {
names = new String[num];
System.out.println("enter employee's name: ");
names[i] = input.nextLine();
//while(names[i].length < 2)
//{
//System.out.println("enter valid employee's name: ");
//names[i] = input.nextLine();
//}
}
for (int j = 0; j < array.length; j++) {
payrate = new double[num];
System.out.println("enter employee's payrate: ");
payrate[j] = input.nextDouble();
while (payrate[j] > 100 || payrate[j] < 0) {
System.out.println("enter valid employee's payrate: ");
payrate[j] = input.nextDouble();
}
}
}
public static void DisplayData(double payrate[], String names[]) {
System.out.printf("Name PayRate\n");
for (int l = 0; l < names.length; l++) {
//for(int i=0;i<names.length;i++)
// {
System.out.print(names[l]);
System.out.printf("\n", payrate[l]);
//}
}
}
public static void main(String[] args) {
GetData();
SortData(payrate);
DisplayData(payrate, names);
}
}
The program Is suppose to print out something like this
Name Payrate
Daniel 54.76
josh 73.12
kyle 12.54
but the program is printing out this
Name PayRate
null
null
null
null
qt
Here are some point you can correct it.
in GetData(), you should put names = new String[num]; anywhere
before loop start, so deos payrate = new double[num];.
in SortData(), why not use double temp;? then you don't have to turn payrate[first] into int type.
in DisplayData(), System.out.printf("\n", payrate[l]); disply
nothing but change line. I think it's better to do like
System.out.printf("Name\tPayRate\n");
for (int l = 0; l < names.length; l++) {
System.out.print(names[l]);
System.out.println("\t"+payrate[l]);
}
well, it's eaiser to explain with code than English. :'(
public static void SortData(double payrate[]) {
int first;
double temp;
String tempString;
int i;
int j;
for (i = payrate.length - 1; i > 0; i--) {
first = 0;
for (j = 1; j <= i; j++) {
if (payrate[j] < payrate[first]) {
first = j;
}
}
temp = payrate[first];
payrate[first] = payrate[i];
payrate[i] = temp;
tempString = names[first];
names[first] = names[i];
names[i] = tempString;
}
}

Not sure where to insert a for loop

I need to code a program that asks the user for the number of spaces between symbols.For eg,
& & &
& & &
& & &
The user will enter an integer and the spacing between the symbols should change.
I have the following code uptil now:
import java.util.Scanner;
public class Spacing
{
public static void main(String[]args)
{
Scanner c=new Scanner(System.in);
System.out.println("Enter spaces between stars: ");
int l=c.nextInt();
String a="*";
String b=" ";
for(int i=0;i<5;i++)
{
for(int j=0;j<l;j++)
{
System.out.print(a+b);
}
System.out.println();
}
}
}
I know how to change the number of symbols and the number of lines.But the problem is how to change the number of spaces.I feel as if there's going to be a for loop involved but I have no clue how to put one in.
Any help would be appreciated.
Here's something that improves readability and introduces some modularity in your code:
import java.util.Scanner;
public class Spacing {
public static void main(String[]args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter spaces between stars: ");
int numSpaces =scanner.nextInt();
String charToDisplay = "*";
String spaces = buildNSpaces(numSpaces);
int numberOfRows = 3;
int numberOfCharactersPerRow = 3;
for(int i = 0; i < numberOfRows; i++) {
for(int j=0; j < numberOfCharactersPerRow; j++) {
System.out.print(charToDisplay+spaces);
}
System.out.println();
}
}
private static String buildNSpaces(final int numSpaces) {
StringBuilder builder = new StringBuilder();
for(int i = 0; i < numSpaces; i++) {
builder.append(" ");
}
return builder.toString();
}
}
for(int i = 0;i < l;i++)
{
System.out.print(" ");
}
code above will print the number of spaces you input.
so you can use it like:
for(int i = 0; i < 3; i++)
{
System.out.print("&");
for(int j = 0; j < l; j++)
System.out.print(" ");
}
this will print out
& & & (there's 3 spaces after the last & also)
if you input 3 in l.
you need another variable and another for loop
try this one
public class Spacing
{
public static void main(String[]args)
{
Scanner c=new Scanner(System.in);
System.out.println("Enter spaces between stars: ");
int l=c.nextInt();
String a="*";
String b=" ";
for(int i=0;i<5;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(a);
for(int k=0;k<l;k++)
{
System.out.print(b);
}
}
System.out.println();
}
}
}

Categories