My array is filled in the beginning with a string. Then the user can enter a new string. I want my array to shift to the right, like {a,x,x,x} should move the a to the right {x,a,x,x} so new entries can move up. When I run my code it puts the entered string in the first position of the array, but in the next step it doesn't move the entered string, but prints out an array only filled with the predefined string. Why doesn't it contain my entered string?
public static void main(String args[]) {
int i;
String n = new String("n");
Scanner sc = new Scanner(System.in);
String a;
String affe [] = new String [5];
Arrays.fill(affe, n);
a = sc.next();
affe[0] = a;
System.out.println(Arrays.toString(affe));
for(i = 0; i<affe.length-1; i++){
affe[i] = affe[i+1];
}
System.out.println(Arrays.toString(affe));
}
Try
Collections.rotate(Arrays.asList(affe), 1);
You're copying the wrong way around.
Change this line:
affe[i] = affe[i+1];
to
affe[i+1] = affe[i];
But you also need to change the order of the loop to go from back to front. Otherwise, each subsequent iteration brings the one value from the start forward to the end. So change the loop to:
for (int i = affe.length - 2; i >= 0; i--) {
affe[i+1] = affe[i];
}
Related
I really need help with my program. I'm trying to make a cumulative grade calculator in java, using arrays and dialog boxes. For some reason, my arrays won't print out the input made by the user which is throwing off my calculations. How can I give it the correct value?
{
// First array - Length
int[] arNumber = null;
int number;
String str;
// Second array - Elements
int numbers;
int[] arNumbers = null;
int total = 0;
int gradeSum = 0;
String str2;
String message = "How many grades will you input in this class?";
str = JOptionPane.showInputDialog(message);
number = Integer.parseInt(str);
arNumber = new int[number];
for(int index = 0; index < arNumber.length; index++)
{
String message2 = "Insert your grade";
str2 = JOptionPane.showInputDialog(message2);
numbers = Integer.parseInt(str2);
arNumbers = new int[numbers];
}
for (int element : arNumbers)
{
// Print array onto console
System.out.println(element);
// Add all elements
gradeSum += element;
// Print grade onto console
System.out.println(gradeSum);
}
total = gradeSum / arNumber.length;
return total;
}```
It looks like you don't need to use two arrays. The line with arNumbers = new int[numbers]; means that arNumbers is getting reinitialized as a new array for every iteration of that loop. Try using arNumber[index] = numbers; to assign the user-entered value into the arNumber array and do away with arNumbers. Then loop over arNumber in the second loop.
Also note that total is declared as an int which will truncate your floating point value, which I'm guessing you don't want. Good luck!
I need to write a program that let's the user write 3 words in the console, then the program reprints those 3 words (one in each line) but also fills out the remaining spaces in each line with dots (".") so the total number of characters in each lines becomes a total of 30 characters.
Example:
Input:
Hello
Me
Overflow
Output:
.........................Hello
............................Me
......................Overflow
This is the code that I currently have which generates an error. I have been given the code (at the bottom) as part of my assignment and need to write the repeatChar method to make it work.
The first thing I did was to add the following commands in the code, in order to save the 3 words into the array threeWord.
threeWord[1] = wordOne;
threeWord[2] = wordTwo;
threeWord[3] = wordThree;
Next, I had to write the method repeatChar, and I decided to use a for-loop to make it repeat dots for each individual line, but I'm having a hard time making it fit with the rest of the code. Any guidance would be much appreciated, thanks.
import java.util.*;
public class FillDots {
private static int LineLength = 30;
public static void main(String[] arg) {
String[] threeWord = new String [3]; // Defines 3 locations to place strings in the array "threeWord"
Scanner console = new Scanner(System.in);
System.out.println("Type in three words:");
String wordOne = console.next();
threeWord[1] = wordOne; // Saves first word to array "threeWord"
String wordTwo = console.next();
threeWord[2] = wordTwo; // Saves second word to array "threeWord"
String wordThree = console.next();
threeWord[3] = wordThree; // Saves third word to array "threeWord"
for(int i = 0; i < threeWord.length; i++) {
System.out.println(repeatChar('.', LineLength - threeWord[i].length()) + threeWord[i]);
}
}
public static String repeatChar(String LineLength) {
for(int j = 0; j < LineLength; j++) {
System.out.print(".");
}
}
}
Besides the index starts from 0, you need return the dots in the repeatChar method:
public static String repeatChar(char repeatChar, int repeatTimes) {
String result = "";
for(int j = 0; j < repeatTimes; j++) {
result += repeatChar;
}
return result;
}
You can use existing library for doing padding
for(String temp:threeWord)
system.out.println(org.apache.commons.lang.StringUtils.leftPad(temp, 10, ".") );
this might simplify your code
String [] board = new String [9];
String [] sequence = new String [8];
sequence[0] = board[0]+board[1]+board[2];
sequence[1] = board[0]+board[3]+board[6];
sequence[2] = board[0]+board[4]+board[8];
sequence[3] = board[1]+board[4]+board[7];
sequence[4] = board[2]+board[5]+board[8];
sequence[5] = board[2]+board[4]+board[6];
sequence[6] = board[3]+board[4]+board[5];
sequence[7] = board[6]+board[7]+board[8];
Say I was to make sequence[0]="XXO";
How could I take sequence[0] and change the the board points so that:
board[0]="X";
board[1]="X";
board[2]="O";
I am trying to run this for loop and I have to initialize the board array before the sequences part as I am printing it out to the screen and can't have the values be null.
for(int i = 0; i < 8; i++
{
if(sequence[i].equals("X"+"X"+" "))
{
sequence[i] = "XXO";
}
}
You can use String::split which return an array of String for example :
String[] board;//you could also to not initialize the array here
//because you will do that in split
String[] sequence = new String[8];
sequence[0] = "XXO";
board = sequence[0].split("");//split and initialize the board array
//print the values
System.out.println(board[0]);
System.out.println(board[1]);
System.out.println(board[2]);
Output
X
X
O
You generally shouldn't store the same data in different ways (the Don't Repeat Yourself principle), sometimes because it leads to a mess like this.
One correct way to do what you want is the following:
board[0] = String.valueOf(sequence[0].charAt(0));
board[1] = String.valueOf(sequence[0].charAt(1));
board[2] = String.valueOf(sequence[0].charAt(2));
As you want only one character as an element in your board array you can use character array instead of String array and then can use
char board[] = new char[9];
board = sequence[0].toCharArray();
I am trying to add the Integer inputted by the user to the ArrayList. It's originally a String, so I converted it to an Integer. I added the Integer to the Arraylist, but now I'm not sure how to display it. I want to be able to keep adding marks, and have all the marks displayed on the screen. I tried a for loop, but I'm not sure what the second parameter would be.
Edit: for (i=0; ... ; i++) -- What would go in the second place?
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
String strInputMark;
int intInputMark;
strInputMark = txtInputMark.getText();
intInputMark = Integer.parseInt(strInputMark);
ArrayList<Integer> Marks = new ArrayList<>();
int intMarks;
Marks.add(intInputMark);
}
Try this for loop:
String output = "";
for(int i = 0; i < Marks.size(); i++){
output += "\n"+Marks.get(i);
}
JOptionPane.showMessageDialog(null, output);
The short answer is i < Marks.size()
for (int i = 0; i < Marks.size(); i++) {
System.out.println(Marks.get(i));
}
You can try this
String strInputMark;
Integer intInputMark;
strInputMark = txtInputMark.getText();
intInputMark = Integer.valueOf(strInputMark);
ArrayList<Integer> Marks = new ArrayList <>();
int intMarks;
Marks.add(intInputMark);
I think the answer is two-fold. First, you need to move 'Marks' outside of the method scope so it can be accessible and continually appended two as input continues. Second, as #Umesh said, Marks.size() will give you the total number of elements in your arraylist.
So the code I have is for a homework assignment where the user inputs a sentence (string) and I need to search through the string and return the smallest word. However, there must be a number inputted at the first spot in the string. Ex: "4 WHAT IS THIS". Output should be "IS" and ignore the number. The only way I figured out how to ignore the number is to make the loop skip over the first spot where the number would be. It works by itself but whenever I put it into the rest of my program it stops working. Is there anyway to make this program cleaner?
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Lexicographically smallest word
String TheSentence = sc.nextLine();
String[] myWords = TheSentence.split(" ");
int shortestLengths, shortestLocation;
shortestLengths = (myWords[1]).length();
shortestLocation = 1;
for (int i = 1; i < myWords.length; i++) {
if ((myWords[i]).length() < shortestLengths) {
shortestLengths = (myWords[i]).length();
shortestLocation = i;
}
}
System.out.println(myWords[shortestLocation]);
}
Inside your for loop (that should start at i = 0), add code like this:
try {
double value = Double.parseDouble(myWords[i]);
} catch (NumberFormatException e) {
// add the rest of your code here
}
The idea is that you try to transform your word to a number and if you fail, it means it's not a number, so you can use the length logic on the word.
The first thing you should do is to create the function you want to use instead of mixing the relevant code for the exercice with things like reading a line from the input stream.
You can test whether a character is a letter using Character.isLetter(char).
A good exercice is to build a solution using only that function and looking at each character separately (String.charAt(int) method) in a loop.
The solution is to remember where the currently shortest word starts and how long it is.
In practice, I would just use regexes like this:
public static String shortestWord(String sentence) {
String shortest = null;
Pattern word = Pattern.compile("\\w+");
Matcher m = word.matcher(sentence);
while (m.find()) {
String candidate = m.group();
if (shortest == null || shortest.length() > candidate.length())
shortest = candidate;
}
return shortest;
}
You could try using substring, e.g.
String result=inputString.substring(1)
'1' being the second letter in the string, substring returning every value save for the first.
The below basically just shortens up your code..other than that it doesn't change much. That being said..it would be much better to create all this in a method called shortestWord() or something. There is really no reason the code below shouldn't work though.
Revised Code:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] myWords = (sc.nextLine()).split(" ");
int shortestLocation = 1
for (int i = 2; i < myWords.length; i++) { // No reason to start at 1 as you have
// already made shortestLocation = 1
if (myWords[i].length() < myWords[shortestLocation].length()) {
shortestLocation = i;
}
}
System.out.println(myWords[shortestLocation]);
}
Suggested Code:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] myWords = (sc.nextLine()).split(" ");
System.out.println("The shortest word is: " + shortestWord(myWords));
}
public static String shortestWord(String[] myWords) {
int shortestLocation = 1
for (int i = 2; i < myWords.length; i++) { // No reason to start at 1 as you have
// already made shortestLocation = 1
if (myWords[i].length() < myWords[shortestLocation].length()) {
shortestLocation = i;
}
}
return myWords[shortestLocation];
}