I have a string input which, that input have a team name and score separated by one space. e.g bb 3 , teamd 5 the winner should be teamd
In order to get the winner team that scored highest score, i'm doing following:
Scanner scanner = new Scanner(System.in);
int cases = scanner.nextInt();
printWinnerTeam(cases);
}
public static void printWinnerTeam(int cases) {
Scanner scanner = new Scanner(System.in);
String str = "";
String winnerTeam = "";
int winnerScore = 0, countedChar = 0;
for (int i = 0; i < cases; i++) {
str += scanner.nextLine();
}
char[] arr = str.toCharArray();
for (int i = 0; i < arr.length; i++) {
countedChar++;
if (arr[i] == ' ') {
if (str.charAt(i + 1) > winnerScore) {
winnerTeam = "";
winnerScore = (int) str.charAt((int) i + 1);
for (int j = 0; j < countedChar; j++) {
winnerTeam += str.charAt(j);
}
countedChar = 0;
} else {
//winnerTeam = "";
countedChar = 0;
}
}
}
System.out.println(winnerTeam);
}
But it's not work prefect, It's print wired result, how to make that work as expect ?
I haven't tried your code, But I would imagine a big problem is the concatenation of str += scanner.nextLine(); The new line is going to be appended straight onto the end of the previous lines number
Have a look at this
Scanner sc = new Scanner(System.in);
int bestScore = Integer.MIN_VALUE;
String team = "Nothing entered";
System.out.println("how many teams");
int count = sc.nextInt();
sc.nextLine();
while (count-- > 0) {
System.out.println("Entered team,score");
String line = sc.nextLine();
String arr [] = line.split(" ");
// check size - TBD
if (Integer.parseInt(arr[1]) > bestScore) {
bestScore = Integer.parseInt(arr[1]);
team = arr[0];
}
}
System.out.println("nest team is " + team + " with a score of " + bestScore);
If I have to do something like that I will do it like this:
import java.util.*;
public class winner {
public static void main (String args []) {
Scanner scanner = new Scanner(System.in);
int cases = scanner.nextInt();
printWinnerTeam(cases);
}
public static void printWinnerTeam(int cases) {
Scanner scanner = new Scanner(System.in);
String winnerTeam = "";
String Team="";
int winnerScore = 0, score = 0;
for (int i = 0; i < cases; i++) {
Team = scanner.next();
score = scanner.nextInt();
if(score > winnerScore){
winnerTeam = Team;
winnerScore = score;
}
}
System.out.println("Winner team" + winnerTeam + "Score:" + winnerScore);
}
}
Related
I have to take a single line of user input, and calculate the average of all the numbers until it reaches -1 using a while loop. An example of user input could be something like 2 -1 6 which is why I've done it this way. I've figured out how to split this into an int array, but I can't figure out how to do the while loop portion.
System.out.println("user input")
String user = scan.nextLine();
String[] string = user.split(" ");
int[] numbers = new int[string.length];
for(int i = 0;i < string.length;i++) {
numbers[i] = Integer.parseInt(string[i]);
}
while ( > -1){
}
Class java.util.Scanner has methods hasNextInt and nextInt.
import java.util.Scanner;
public class Averages {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter series of integers on single line separated by spaces.");
System.out.println("For example: 2 -1 6");
int sum = 0;
int count = 0;
while (scan.hasNextInt()) {
int num = scan.nextInt();
if (num == -1) {
break;
}
sum += num;
count++;
}
if (count > 0) {
double average = sum / (double) count;
System.out.println("Average: " + average);
}
else {
System.out.println("Invalid input.");
}
}
}
Note that you need to cast count to a double when calculating the average otherwise integer division will be performed and that will not give the correct average.
I am assuming you mean, when user input number is -1. we should take average of all number before -1. that is was I am doing here.
System.out.println("user input")
String user = scan.nextLine();
int totalSum = 0;
double avg = 0;
String[] string = user.split(" ");
int[] numbers = new int[string.length];
for(int i = 0;i < string.length;i++) {
numbers[i] = Integer.parseInt(string[i]);
if(numbers[i]==-1){
avg = (double)totalSum / i;
break;
}
totalSum += numbers[i];
}
With only while loop
System.out.println("user input");
String user = scan.nextLine();
int totalSum = 0;
double avg = 0;
String[] string = user.split(" ");
int[] numbers = new int[string.length];
int i = 0;
numbers[i] = Integer.parseInt(string[i]);
while(numbers[i]!=-1) {
totalSum += numbers[i];
i++;
numbers[i] = Integer.parseInt(string[i]);
}
avg = (double)totalSum / i;
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("user input");
String user = scan.nextLine();
boolean found = false;
Double average = 0.0;
String[] string = user.split(" ");
int[] numbers = new int[string.length];
for(int i = 0;i < string.length && found == false ;i++) {
numbers[i] = Integer.parseInt(string[i]);
}
int t = 0;
while (found == false && t < string.length){
if(numbers[t] == - 1){
average = average/t;
found = true;
}
else{
average = (Double) average + numbers[t];
t++;
}
}
System.out.println("Average = " + average);
}
}
I am attempting to write a program that picks a random word from a text file, scrambles it, and allows the user to unscramble it by swapping 2 index locations at a time.
I have the program to the point where it grabs a random word from the text file and prints it out with the index numbers above it.
I am having trouble figuring out how to:
Get the word scrambled before it prints out on screen, and
How to get the user to be able to loop through swapping 2 indexes at a time until the word is unscrambled.
Is there a method I can write that will perform these actions?
Here is my code so far.
import java.io.*;
import java.util.*;
public class Midterm { // class header
public static void main(String[] args) { // Method header
int option = 0;
Scanner input = new Scanner(System.in);
int scrambled;
int counter = 0;
int index1;
int index2;
String[] words = readArray("words.txt");
/*
* Picks a random word from the array built from words.txt file. Prints
* index with word beneath it.
*/
int randWord = (int) (Math.random() * 11);
for (int j = 0; j < words[randWord].length(); j = j + 1) {
System.out.print(j);
}
System.out.print("\n");
char[] charArray = words[randWord].toCharArray();
for (char c : charArray) {
System.out.print(c);
}
/*
* Prompt the user for input to play game or quit.
*/
System.out.println("\n");
System.out.println("Enter 1 to swap a par of letters.");
System.out.println("Enter 2 to show the solution and quit.");
System.out.println("Enter 3 to quit.");
if (input.hasNextInt()) {
option = input.nextInt();
counter++;
}
else {
option = 3;
}
System.out.println("");
if (option == 1) {
System.out.println("Enter the two index locations to swap separated by a space. ");
index1 = 0;
index2 = 0;
if (input.hasNextInt()) {
index1 = input.nextInt();
}
else {
System.out.println("Please enter only numbers.");
}
if (input.hasNextInt()) {
index2 = input.nextInt();
}
else {
System.out.println("Please enter only numbers.");
}
}
}
// end main
public static String[] readArray(String file) {
// Step 1:
// Count how many lines are in the file
// Step 2:
// Create the array and copy the elements into it
// Step 1:
int ctr = 0;
try {
Scanner s1 = new Scanner(new File(file));
while (s1.hasNextLine()) {
ctr = ctr + 1;
s1.nextLine();
}
String[] words = new String[ctr];
// Step 2:
Scanner s2 = new Scanner(new File(file));
for (int i = 0; i < ctr; i = i + 1) {
words[i] = s2.next();
}
return words;
} catch (FileNotFoundException e) {
}
return null;
}
}
I made some pretty major modifications to your code, including adding a scrambler method. The program is almost perfect, its just that your file "words.txt" can not hold words with repeat letters. For example, yellow, green, and purple won't unscramble correctly, but white, gray, blue, orange, or red will work fine. Other than that, the program works well. It chooses a random word, then when it is solved, chooses a different word, changing the last word to null, so it does not get picked again. Here's the program:
import java.io.*;
import java.util.*;
public class Experiments { // class header
private static String[] words = readArray("/Users/UserName/Desktop/words.txt"); //change to your location of the file
public static void main(String[] args) { // Method header
int option = 0;
Scanner input = new Scanner(System.in);
int counter = 0;
String scrambledWord;
int index1;
int index2;
Random rand = new Random();
int randWord = rand.nextInt(words.length);
for (int j = 0; j < words[randWord].length(); j += 1) {
System.out.print(j);
}
System.out.print("\n");
scrambledWord = scrambler(words[randWord]);
System.out.println(scrambledWord);
System.out.println("\n");
System.out.println("Enter 1 to swap a pair of letters.");
System.out.println("Enter 2 to show the solution and quit.");
System.out.println("Enter 3 to quit.");
option = input.nextInt();
if (option == 1) {
while (!scrambledWord.equals(words[randWord])) {
index1 = 0;
index2 = 0;
boolean validOption = false;
System.out.println("Enter the two index locations to swap separated by a space.");
while (!validOption) {
if (input.hasNextInt()) {
index1 = input.nextInt();
index2 = input.nextInt();
validOption = true;
}
else {
System.out.println("Please enter only numbers.");
validOption = false;
break;
}
}
String letter1 = scrambledWord.substring(index1, index1+1);
String letter2 = scrambledWord.substring(index2, index2+1);
System.out.println("replacing " + letter1 + " with " + letter2 + "...");
if (index1 < index2) {
scrambledWord = scrambledWord.replaceFirst(letter2, letter1);
scrambledWord = scrambledWord.replaceFirst(letter1, letter2);
} else {
scrambledWord = scrambledWord.replaceFirst(letter1, letter2);
scrambledWord = scrambledWord.replaceFirst(letter2, letter1);
}
System.out.println();
for (int j = 0; j < words[randWord].length(); j += 1) {
System.out.print(j);
}
System.out.println("\n"+scrambledWord);
System.out.println();
counter++;
if (scrambledWord.equals(words[randWord])){
System.out.println("You did it! The word was " + words[randWord]);
System.out.println("You got it with " + counter + " replacements!");
words[randWord] = null;
if (words.length == 0){
System.out.println("I'm all out of words. You win!");
System.exit(0);
} else {
main(args);
}
}
}
} else if (option == 2) {
System.out.println(words[randWord]);
System.exit(0);
} else {
System.exit(0);
}
input.close();
}
//scrambles the word given to it
private static String scrambler(String word) {
String scrambled = "";
Random rand = new Random();
int length;
int index;
String letter;
String firststring;
String secondstring;
while (word.length()>0) {
length = word.length();
index = rand.nextInt(length);
letter = word.substring(index, index+1);
firststring = word.substring(0, index);
secondstring = word.substring(index+1);
word = firststring + secondstring;
scrambled += letter;
}
return scrambled;
}
public static String[] readArray(String file) {
int ctr = 0;
try {
Scanner s1 = new Scanner(new File(file));
while (s1.hasNextLine()) {
ctr = ctr + 1;
s1.nextLine();
}
String[] words = new String[ctr];
// Step 2:
Scanner s2 = new Scanner(new File(file));
for (int i = 0; i < ctr; i = i + 1) {
words[i] = s2.next();
}
return words;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
And here's the list of words in the file words.txt(I pretty much wrote down whatever popped into my head that did not have repeat letters):
orange
red
brown
black
white
blue
tiger
horse
bugs
stack
overflow
pathfinder
extra
zealous
wisdom
under
above
death
life
second
first
frost
forest
These are obviously not the only words that can go in, you can add as many as you want, as long as they do not have 2 occurrences of the same letter.
You are reading the file incorrectly. Do
public static String[] readArray(String file) {
int ctr = 0;
try {
Scanner s1 = new Scanner(new File(file));
while (s1.hasNext()) {
ctr = ctr + 1;
s1.next();
}
//..rest of code
Input text: are you ready
Output text: ArE YoU ReAdY
Help me what i am missing.
Below is the code which I am using:
import java.util.Scanner;
import java.lang.*;
public class Testdemo{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
String result = "";
System.out.println("enter the string");
String name =sc.nextLine();
String[] words = name.split("\\s");
for(int i=0;i<words.length;i++){
String med = words[i];
for(int j=0;j<med.length;j++){
if(i%2 == 0){
result = result + Character.toUpperCase(words[i].charAt(0)) + words[i].substring(1) + " ";
}
else{
result = result + Character.toLowerCase(words[i].charAt(0)) + words[i].substring(1) + " ";
}
}
}
System.out.println(result);
}
}
Scanner sc = new Scanner(System.in);
StringBuffer result = new StringBuffer();
System.out.println("enter the string");
String name = sc.nextLine();
String[] words = name.split("\\s");
for (int i = 0; i < words.length; i++) {
String med = words[i];
for (int j = 0; j < med.length(); j++) {
if (j % 2 == 0) {
result.append(Character.toUpperCase(words[i].charAt(j)));
} else {
result.append(Character.toLowerCase(words[i].charAt(j)));
}
}
result.append(" ");
}
System.out.println(result);
How to find common suffix in java by using method
public static String commonSuffix (String s1, String s2)
I can't return the result in method. Please help me
import java.util.Scanner;
public class ders1 {
public static void main(String[] args) {
//HW3 Topic 3
Scanner input = new Scanner(System.in);
String reverse1="";
String reverse2="";
System.out.println("Please enter the first string: ");
String s1=input.nextLine();
System.out.println("Please enter the second string: ");
String s2=input.nextLine();
int l1=reverse1.length();
int l2=reverse2.length();
for ( int i = s1.length() - 1 ; i >= 0 ; i-- )
{
reverse1 = reverse1 + s1.charAt(i);
}
for ( int i = s2.length() - 1 ; i >= 0 ; i-- )
{
reverse2 = reverse2 + s2.charAt(i);
}
if(l1<l2){
int l3=l2;
System.out.println(reverse1 + " " + reverse2);
System.out.println(commonSuffix(reverse1,reverse2,l3));
}
else {
int l3=l1;
System.out.println(reverse1 + " " + reverse2);
System.out.println(commonSuffix(reverse1,reverse2,l3));
}
}
public static String commonSuffix (String reverse1, String reverse2,int l3){
String suffixies="";
for(int k=0; k<=l3 ; k++){
if(reverse1.charAt(k)!=reverse2.charAt(k)){
}
else{
suffixies+=reverse1.charAt(k);
}
}
return suffixies;
}
}
Can someone help me fix this code??
Your issue is that you return inside of the for loop. You should return after the for loop terminates.
Please see the following code (I have tested it):
import java.util.Scanner;
public class ders1 {
public static void main(String[] args) {
// HW3 Topic 3
Scanner input = new Scanner(System.in);
String reverse1 = "";
String reverse2 = "";
System.out.println("Please enter the first string: ");
String s1 = input.nextLine();
System.out.println("Please enter the second string: ");
String s2 = input.nextLine();
for (int i = s1.length() - 1; i >= 0; i--) {
reverse1 = reverse1 + s1.charAt(i);
}
for (int i = s2.length() - 1; i >= 0; i--) {
reverse2 = reverse2 + s2.charAt(i);
}
int l1 = reverse1.length();
int l2 = reverse2.length();
if (l1 < l2) {
int l3 = l1;
System.out.println(reverse1 + " " + reverse2);
System.out.println(commonSuffix(reverse1, reverse2, l3));
} else {
int l3 = l2;
System.out.println(reverse1 + " " + reverse2);
System.out.println(commonSuffix(reverse1, reverse2, l3));
}
}
public static String commonSuffix(String reverse1, String reverse2, int l3) {
String suffixies = "";
for (int k = 0; k < l3; k++) {
if (reverse1.charAt(k) != reverse2.charAt(k)) {
break;
} else {
suffixies += reverse1.charAt(k);
}
}
// Reverse again
String reverse = "";
for (int i = suffixies.length() - 1; i >= 0; i--) {
reverse = reverse + suffixies.charAt(i);
}
return reverse;
}
}
Output:
Please enter the first string:
caption
Please enter the second string:
action
noitpac noitca
tion
This could be the best
**
package com.tm;
import java.util.Scanner;
public class CommSuffix {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String str[] = scan.nextLine().split(",");
String commSufffix=null;
if(str[0].trim().length() > str[1].trim().length()) {
String temp = str[0].trim();
str[0] = str[1].trim();
str[1] = temp;
}
for(int i=0;i<str[0].length();i++) {
String subStr = str[0].substring(i,str[0].length());
if(str[1].endsWith(subStr)) {
commSufffix = subStr;
break;
}
}
System.out.println(commSufffix);
}
} **
So I have to read a sequence of numbers from the console ( 1 to 50 numbers), none of which are equal and print out the numbers for which is true that a|b == c|d (example: 5|32 == 53|2), but I get an NubmferFormatException each time. Why?
import java.util.Scanner;
public class StuckNumbers {
public static void main(String[] args) {
// create Scanner
Scanner input = new Scanner(System.in);
// input count and declare array
System.out.println("input number of numbers");
int count = input.nextInt();
int[] numbers = new int[count];
// check if count is between 1 and 50
if (count < 1 && count > 50) {
System.out.println("Wrong input. Input a number between 1 and 50");
count = input.nextInt();
}
// input n numbers
for (int i : numbers) {
i = input.nextInt();
// check if i = j
for (int j : numbers) {
if (i == j) {
System.out
.println("All numbers must be dist75inct. Try again.");
i = input.nextInt();
}
}
}
for (int i = 0; i < count; i++) {
for (int j = 0; j < count; j++) {
if (stuckNumbers(numbers[i], numbers[j]) == stuckNumbers(
numbers[j], numbers[i])) {
System.out.println(i + "|" + j + " == " + j + "|" + i);
}
}
}
input.close();
}
public static int stuckNumbers(int a, int b) {
String firstNum = "a";
String secondNum = "b";
String res = "ab";
int result = Integer.parseInt(res);
return result;
}
}
Look at these lines:
String res = "ab";
int result = Integer.parseInt(res);
"ab" is not a number, so you're going to get a NumberFormatException when you try to parse it as an integer.
Change the firstNum and SecondNum variables from "a" and "b" to Integer.toString(a); OR String.valueOf(a); and similar for b.
public static int stuckNumbers(int a, int b) {
String firstNum = String.valueOf(a);
String secondNum = String.valueOf(b);
String res = "";
res.concat(firstNum);
res.concat(secondNum);
int result = Integer.parseInt(res);
return result;
}
I hope this will remove any Exception being thrown.